babylon.max.js 2.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. })();
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. })();
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. })();
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. })();
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.toVector3 = function () {
  1188. return new Vector3(this.x, this.y, this.z);
  1189. };
  1190. Vector4.prototype.clone = function () {
  1191. return new Vector4(this.x, this.y, this.z, this.w);
  1192. };
  1193. Vector4.prototype.copyFrom = function (source) {
  1194. this.x = source.x;
  1195. this.y = source.y;
  1196. this.z = source.z;
  1197. this.w = source.w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1201. this.x = x;
  1202. this.y = y;
  1203. this.z = z;
  1204. this.w = w;
  1205. return this;
  1206. };
  1207. // Statics
  1208. Vector4.FromArray = function (array, offset) {
  1209. if (!offset) {
  1210. offset = 0;
  1211. }
  1212. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1213. };
  1214. Vector4.FromArrayToRef = function (array, offset, result) {
  1215. result.x = array[offset];
  1216. result.y = array[offset + 1];
  1217. result.z = array[offset + 2];
  1218. result.w = array[offset + 3];
  1219. };
  1220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1221. result.x = array[offset];
  1222. result.y = array[offset + 1];
  1223. result.z = array[offset + 2];
  1224. result.w = array[offset + 3];
  1225. };
  1226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1227. result.x = x;
  1228. result.y = y;
  1229. result.z = z;
  1230. result.w = w;
  1231. };
  1232. Vector4.Zero = function () {
  1233. return new Vector4(0, 0, 0, 0);
  1234. };
  1235. Vector4.Normalize = function (vector) {
  1236. var result = Vector4.Zero();
  1237. Vector4.NormalizeToRef(vector, result);
  1238. return result;
  1239. };
  1240. Vector4.NormalizeToRef = function (vector, result) {
  1241. result.copyFrom(vector);
  1242. result.normalize();
  1243. };
  1244. Vector4.Minimize = function (left, right) {
  1245. var min = left.clone();
  1246. min.MinimizeInPlace(right);
  1247. return min;
  1248. };
  1249. Vector4.Maximize = function (left, right) {
  1250. var max = left.clone();
  1251. max.MaximizeInPlace(right);
  1252. return max;
  1253. };
  1254. Vector4.Distance = function (value1, value2) {
  1255. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1256. };
  1257. Vector4.DistanceSquared = function (value1, value2) {
  1258. var x = value1.x - value2.x;
  1259. var y = value1.y - value2.y;
  1260. var z = value1.z - value2.z;
  1261. var w = value1.w - value2.w;
  1262. return (x * x) + (y * y) + (z * z) + (w * w);
  1263. };
  1264. Vector4.Center = function (value1, value2) {
  1265. var center = value1.add(value2);
  1266. center.scaleInPlace(0.5);
  1267. return center;
  1268. };
  1269. return Vector4;
  1270. })();
  1271. BABYLON.Vector4 = Vector4;
  1272. var Quaternion = (function () {
  1273. function Quaternion(x, y, z, w) {
  1274. if (x === void 0) { x = 0; }
  1275. if (y === void 0) { y = 0; }
  1276. if (z === void 0) { z = 0; }
  1277. if (w === void 0) { w = 1; }
  1278. this.x = x;
  1279. this.y = y;
  1280. this.z = z;
  1281. this.w = w;
  1282. }
  1283. Quaternion.prototype.toString = function () {
  1284. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1285. };
  1286. Quaternion.prototype.asArray = function () {
  1287. return [this.x, this.y, this.z, this.w];
  1288. };
  1289. Quaternion.prototype.equals = function (otherQuaternion) {
  1290. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1291. };
  1292. Quaternion.prototype.clone = function () {
  1293. return new Quaternion(this.x, this.y, this.z, this.w);
  1294. };
  1295. Quaternion.prototype.copyFrom = function (other) {
  1296. this.x = other.x;
  1297. this.y = other.y;
  1298. this.z = other.z;
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1303. this.x = x;
  1304. this.y = y;
  1305. this.z = z;
  1306. this.w = w;
  1307. return this;
  1308. };
  1309. Quaternion.prototype.add = function (other) {
  1310. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1311. };
  1312. Quaternion.prototype.subtract = function (other) {
  1313. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1314. };
  1315. Quaternion.prototype.scale = function (value) {
  1316. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1317. };
  1318. Quaternion.prototype.multiply = function (q1) {
  1319. var result = new Quaternion(0, 0, 0, 1.0);
  1320. this.multiplyToRef(q1, result);
  1321. return result;
  1322. };
  1323. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1324. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1325. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1326. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1327. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1328. result.copyFromFloats(x, y, z, w);
  1329. return this;
  1330. };
  1331. Quaternion.prototype.multiplyInPlace = function (q1) {
  1332. this.multiplyToRef(q1, this);
  1333. return this;
  1334. };
  1335. Quaternion.prototype.conjugateToRef = function (ref) {
  1336. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1337. return this;
  1338. };
  1339. Quaternion.prototype.conjugateInPlace = function () {
  1340. this.x *= -1;
  1341. this.y *= -1;
  1342. this.z *= -1;
  1343. return this;
  1344. };
  1345. Quaternion.prototype.conjugate = function () {
  1346. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1347. return result;
  1348. };
  1349. Quaternion.prototype.length = function () {
  1350. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1351. };
  1352. Quaternion.prototype.normalize = function () {
  1353. var length = 1.0 / this.length();
  1354. this.x *= length;
  1355. this.y *= length;
  1356. this.z *= length;
  1357. this.w *= length;
  1358. return this;
  1359. };
  1360. Quaternion.prototype.toEulerAngles = function (order) {
  1361. if (order === void 0) { order = "YZX"; }
  1362. var result = Vector3.Zero();
  1363. this.toEulerAnglesToRef(result, order);
  1364. return result;
  1365. };
  1366. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1367. if (order === void 0) { order = "YZX"; }
  1368. var heading, attitude, bank;
  1369. var x = this.x, y = this.y, z = this.z, w = this.w;
  1370. switch (order) {
  1371. case "YZX":
  1372. var test = x * y + z * w;
  1373. if (test > 0.499) {
  1374. heading = 2 * Math.atan2(x, w);
  1375. attitude = Math.PI / 2;
  1376. bank = 0;
  1377. }
  1378. if (test < -0.499) {
  1379. heading = -2 * Math.atan2(x, w);
  1380. attitude = -Math.PI / 2;
  1381. bank = 0;
  1382. }
  1383. if (isNaN(heading)) {
  1384. var sqx = x * x;
  1385. var sqy = y * y;
  1386. var sqz = z * z;
  1387. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1388. attitude = Math.asin(2 * test); // attitude
  1389. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1390. }
  1391. break;
  1392. default:
  1393. throw new Error("Euler order " + order + " not supported yet.");
  1394. }
  1395. result.y = heading;
  1396. result.z = attitude;
  1397. result.x = bank;
  1398. return this;
  1399. };
  1400. ;
  1401. Quaternion.prototype.toRotationMatrix = function (result) {
  1402. var xx = this.x * this.x;
  1403. var yy = this.y * this.y;
  1404. var zz = this.z * this.z;
  1405. var xy = this.x * this.y;
  1406. var zw = this.z * this.w;
  1407. var zx = this.z * this.x;
  1408. var yw = this.y * this.w;
  1409. var yz = this.y * this.z;
  1410. var xw = this.x * this.w;
  1411. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1412. result.m[1] = 2.0 * (xy + zw);
  1413. result.m[2] = 2.0 * (zx - yw);
  1414. result.m[3] = 0;
  1415. result.m[4] = 2.0 * (xy - zw);
  1416. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1417. result.m[6] = 2.0 * (yz + xw);
  1418. result.m[7] = 0;
  1419. result.m[8] = 2.0 * (zx + yw);
  1420. result.m[9] = 2.0 * (yz - xw);
  1421. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1422. result.m[11] = 0;
  1423. result.m[12] = 0;
  1424. result.m[13] = 0;
  1425. result.m[14] = 0;
  1426. result.m[15] = 1.0;
  1427. return this;
  1428. };
  1429. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1430. Quaternion.FromRotationMatrixToRef(matrix, this);
  1431. return this;
  1432. };
  1433. // Statics
  1434. Quaternion.FromRotationMatrix = function (matrix) {
  1435. var result = new Quaternion();
  1436. Quaternion.FromRotationMatrixToRef(matrix, result);
  1437. return result;
  1438. };
  1439. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1440. var data = matrix.m;
  1441. var m11 = data[0], m12 = data[4], m13 = data[8];
  1442. var m21 = data[1], m22 = data[5], m23 = data[9];
  1443. var m31 = data[2], m32 = data[6], m33 = data[10];
  1444. var trace = m11 + m22 + m33;
  1445. var s;
  1446. if (trace > 0) {
  1447. s = 0.5 / Math.sqrt(trace + 1.0);
  1448. result.w = 0.25 / s;
  1449. result.x = (m32 - m23) * s;
  1450. result.y = (m13 - m31) * s;
  1451. result.z = (m21 - m12) * s;
  1452. }
  1453. else if (m11 > m22 && m11 > m33) {
  1454. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1455. result.w = (m32 - m23) / s;
  1456. result.x = 0.25 * s;
  1457. result.y = (m12 + m21) / s;
  1458. result.z = (m13 + m31) / s;
  1459. }
  1460. else if (m22 > m33) {
  1461. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1462. result.w = (m13 - m31) / s;
  1463. result.x = (m12 + m21) / s;
  1464. result.y = 0.25 * s;
  1465. result.z = (m23 + m32) / s;
  1466. }
  1467. else {
  1468. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1469. result.w = (m21 - m12) / s;
  1470. result.x = (m13 + m31) / s;
  1471. result.y = (m23 + m32) / s;
  1472. result.z = 0.25 * s;
  1473. }
  1474. };
  1475. Quaternion.Inverse = function (q) {
  1476. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1477. };
  1478. Quaternion.Identity = function () {
  1479. return new Quaternion(0, 0, 0, 1);
  1480. };
  1481. Quaternion.RotationAxis = function (axis, angle) {
  1482. var result = new Quaternion();
  1483. var sin = Math.sin(angle / 2);
  1484. axis.normalize();
  1485. result.w = Math.cos(angle / 2);
  1486. result.x = axis.x * sin;
  1487. result.y = axis.y * sin;
  1488. result.z = axis.z * sin;
  1489. return result;
  1490. };
  1491. Quaternion.FromArray = function (array, offset) {
  1492. if (!offset) {
  1493. offset = 0;
  1494. }
  1495. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1496. };
  1497. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1498. var result = new Quaternion();
  1499. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1500. return result;
  1501. };
  1502. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1503. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1504. var halfRoll = roll * 0.5;
  1505. var halfPitch = pitch * 0.5;
  1506. var halfYaw = yaw * 0.5;
  1507. var sinRoll = Math.sin(halfRoll);
  1508. var cosRoll = Math.cos(halfRoll);
  1509. var sinPitch = Math.sin(halfPitch);
  1510. var cosPitch = Math.cos(halfPitch);
  1511. var sinYaw = Math.sin(halfYaw);
  1512. var cosYaw = Math.cos(halfYaw);
  1513. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1514. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1515. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1516. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1517. };
  1518. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1519. var result = new Quaternion();
  1520. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1521. return result;
  1522. };
  1523. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1524. // Produces a quaternion from Euler angles in the z-x-z orientation
  1525. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1526. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1527. var halfBeta = beta * 0.5;
  1528. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1529. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1530. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1531. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1532. };
  1533. Quaternion.Slerp = function (left, right, amount) {
  1534. var num2;
  1535. var num3;
  1536. var num = amount;
  1537. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1538. var flag = false;
  1539. if (num4 < 0) {
  1540. flag = true;
  1541. num4 = -num4;
  1542. }
  1543. if (num4 > 0.999999) {
  1544. num3 = 1 - num;
  1545. num2 = flag ? -num : num;
  1546. }
  1547. else {
  1548. var num5 = Math.acos(num4);
  1549. var num6 = (1.0 / Math.sin(num5));
  1550. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1551. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1552. }
  1553. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1554. };
  1555. return Quaternion;
  1556. })();
  1557. BABYLON.Quaternion = Quaternion;
  1558. var Matrix = (function () {
  1559. function Matrix() {
  1560. this.m = new Float32Array(16);
  1561. }
  1562. // Properties
  1563. Matrix.prototype.isIdentity = function () {
  1564. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1565. return false;
  1566. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1567. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1568. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1569. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1570. return false;
  1571. return true;
  1572. };
  1573. Matrix.prototype.determinant = function () {
  1574. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1575. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1576. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1577. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1578. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1579. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1580. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1581. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1582. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1583. };
  1584. // Methods
  1585. Matrix.prototype.toArray = function () {
  1586. return this.m;
  1587. };
  1588. Matrix.prototype.asArray = function () {
  1589. return this.toArray();
  1590. };
  1591. Matrix.prototype.invert = function () {
  1592. this.invertToRef(this);
  1593. return this;
  1594. };
  1595. Matrix.prototype.reset = function () {
  1596. for (var index = 0; index < 16; index++) {
  1597. this.m[index] = 0;
  1598. }
  1599. return this;
  1600. };
  1601. Matrix.prototype.add = function (other) {
  1602. var result = new Matrix();
  1603. this.addToRef(other, result);
  1604. return result;
  1605. };
  1606. Matrix.prototype.addToRef = function (other, result) {
  1607. for (var index = 0; index < 16; index++) {
  1608. result.m[index] = this.m[index] + other.m[index];
  1609. }
  1610. return this;
  1611. };
  1612. Matrix.prototype.addToSelf = function (other) {
  1613. for (var index = 0; index < 16; index++) {
  1614. this.m[index] += other.m[index];
  1615. }
  1616. return this;
  1617. };
  1618. Matrix.prototype.invertToRef = function (other) {
  1619. var l1 = this.m[0];
  1620. var l2 = this.m[1];
  1621. var l3 = this.m[2];
  1622. var l4 = this.m[3];
  1623. var l5 = this.m[4];
  1624. var l6 = this.m[5];
  1625. var l7 = this.m[6];
  1626. var l8 = this.m[7];
  1627. var l9 = this.m[8];
  1628. var l10 = this.m[9];
  1629. var l11 = this.m[10];
  1630. var l12 = this.m[11];
  1631. var l13 = this.m[12];
  1632. var l14 = this.m[13];
  1633. var l15 = this.m[14];
  1634. var l16 = this.m[15];
  1635. var l17 = (l11 * l16) - (l12 * l15);
  1636. var l18 = (l10 * l16) - (l12 * l14);
  1637. var l19 = (l10 * l15) - (l11 * l14);
  1638. var l20 = (l9 * l16) - (l12 * l13);
  1639. var l21 = (l9 * l15) - (l11 * l13);
  1640. var l22 = (l9 * l14) - (l10 * l13);
  1641. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1642. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1643. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1644. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1645. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1646. var l28 = (l7 * l16) - (l8 * l15);
  1647. var l29 = (l6 * l16) - (l8 * l14);
  1648. var l30 = (l6 * l15) - (l7 * l14);
  1649. var l31 = (l5 * l16) - (l8 * l13);
  1650. var l32 = (l5 * l15) - (l7 * l13);
  1651. var l33 = (l5 * l14) - (l6 * l13);
  1652. var l34 = (l7 * l12) - (l8 * l11);
  1653. var l35 = (l6 * l12) - (l8 * l10);
  1654. var l36 = (l6 * l11) - (l7 * l10);
  1655. var l37 = (l5 * l12) - (l8 * l9);
  1656. var l38 = (l5 * l11) - (l7 * l9);
  1657. var l39 = (l5 * l10) - (l6 * l9);
  1658. other.m[0] = l23 * l27;
  1659. other.m[4] = l24 * l27;
  1660. other.m[8] = l25 * l27;
  1661. other.m[12] = l26 * l27;
  1662. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1663. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1664. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1665. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1666. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1667. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1668. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1669. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1670. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1671. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1672. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1673. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1674. return this;
  1675. };
  1676. Matrix.prototype.setTranslation = function (vector3) {
  1677. this.m[12] = vector3.x;
  1678. this.m[13] = vector3.y;
  1679. this.m[14] = vector3.z;
  1680. return this;
  1681. };
  1682. Matrix.prototype.getTranslation = function () {
  1683. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1684. };
  1685. Matrix.prototype.multiply = function (other) {
  1686. var result = new Matrix();
  1687. this.multiplyToRef(other, result);
  1688. return result;
  1689. };
  1690. Matrix.prototype.copyFrom = function (other) {
  1691. for (var index = 0; index < 16; index++) {
  1692. this.m[index] = other.m[index];
  1693. }
  1694. return this;
  1695. };
  1696. Matrix.prototype.copyToArray = function (array, offset) {
  1697. if (offset === void 0) { offset = 0; }
  1698. for (var index = 0; index < 16; index++) {
  1699. array[offset + index] = this.m[index];
  1700. }
  1701. return this;
  1702. };
  1703. Matrix.prototype.multiplyToRef = function (other, result) {
  1704. this.multiplyToArray(other, result.m, 0);
  1705. return this;
  1706. };
  1707. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1708. var tm0 = this.m[0];
  1709. var tm1 = this.m[1];
  1710. var tm2 = this.m[2];
  1711. var tm3 = this.m[3];
  1712. var tm4 = this.m[4];
  1713. var tm5 = this.m[5];
  1714. var tm6 = this.m[6];
  1715. var tm7 = this.m[7];
  1716. var tm8 = this.m[8];
  1717. var tm9 = this.m[9];
  1718. var tm10 = this.m[10];
  1719. var tm11 = this.m[11];
  1720. var tm12 = this.m[12];
  1721. var tm13 = this.m[13];
  1722. var tm14 = this.m[14];
  1723. var tm15 = this.m[15];
  1724. var om0 = other.m[0];
  1725. var om1 = other.m[1];
  1726. var om2 = other.m[2];
  1727. var om3 = other.m[3];
  1728. var om4 = other.m[4];
  1729. var om5 = other.m[5];
  1730. var om6 = other.m[6];
  1731. var om7 = other.m[7];
  1732. var om8 = other.m[8];
  1733. var om9 = other.m[9];
  1734. var om10 = other.m[10];
  1735. var om11 = other.m[11];
  1736. var om12 = other.m[12];
  1737. var om13 = other.m[13];
  1738. var om14 = other.m[14];
  1739. var om15 = other.m[15];
  1740. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1741. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1742. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1743. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1744. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1745. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1746. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1747. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1748. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1749. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1750. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1751. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1752. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1753. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1754. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1755. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1756. return this;
  1757. };
  1758. Matrix.prototype.equals = function (value) {
  1759. return value &&
  1760. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1761. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1762. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1763. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1764. };
  1765. Matrix.prototype.clone = function () {
  1766. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1767. };
  1768. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1769. translation.x = this.m[12];
  1770. translation.y = this.m[13];
  1771. translation.z = this.m[14];
  1772. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1773. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1774. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1775. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1776. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1777. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1778. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1779. rotation.x = 0;
  1780. rotation.y = 0;
  1781. rotation.z = 0;
  1782. rotation.w = 1;
  1783. return false;
  1784. }
  1785. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1786. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1787. return true;
  1788. };
  1789. // Statics
  1790. Matrix.FromArray = function (array, offset) {
  1791. var result = new Matrix();
  1792. if (!offset) {
  1793. offset = 0;
  1794. }
  1795. Matrix.FromArrayToRef(array, offset, result);
  1796. return result;
  1797. };
  1798. Matrix.FromArrayToRef = function (array, offset, result) {
  1799. for (var index = 0; index < 16; index++) {
  1800. result.m[index] = array[index + offset];
  1801. }
  1802. };
  1803. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1804. for (var index = 0; index < 16; index++) {
  1805. result.m[index] = array[index + offset] * scale;
  1806. }
  1807. };
  1808. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1809. result.m[0] = initialM11;
  1810. result.m[1] = initialM12;
  1811. result.m[2] = initialM13;
  1812. result.m[3] = initialM14;
  1813. result.m[4] = initialM21;
  1814. result.m[5] = initialM22;
  1815. result.m[6] = initialM23;
  1816. result.m[7] = initialM24;
  1817. result.m[8] = initialM31;
  1818. result.m[9] = initialM32;
  1819. result.m[10] = initialM33;
  1820. result.m[11] = initialM34;
  1821. result.m[12] = initialM41;
  1822. result.m[13] = initialM42;
  1823. result.m[14] = initialM43;
  1824. result.m[15] = initialM44;
  1825. };
  1826. Matrix.prototype.getRow = function (index) {
  1827. if (index < 0 || index > 3) {
  1828. return null;
  1829. }
  1830. var i = index * 4;
  1831. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  1832. };
  1833. Matrix.prototype.setRow = function (index, row) {
  1834. if (index < 0 || index > 3) {
  1835. return this;
  1836. }
  1837. var i = index * 4;
  1838. this.m[i + 0] = row.x;
  1839. this.m[i + 1] = row.y;
  1840. this.m[i + 2] = row.z;
  1841. this.m[i + 3] = row.w;
  1842. return this;
  1843. };
  1844. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1845. var result = new Matrix();
  1846. result.m[0] = initialM11;
  1847. result.m[1] = initialM12;
  1848. result.m[2] = initialM13;
  1849. result.m[3] = initialM14;
  1850. result.m[4] = initialM21;
  1851. result.m[5] = initialM22;
  1852. result.m[6] = initialM23;
  1853. result.m[7] = initialM24;
  1854. result.m[8] = initialM31;
  1855. result.m[9] = initialM32;
  1856. result.m[10] = initialM33;
  1857. result.m[11] = initialM34;
  1858. result.m[12] = initialM41;
  1859. result.m[13] = initialM42;
  1860. result.m[14] = initialM43;
  1861. result.m[15] = initialM44;
  1862. return result;
  1863. };
  1864. Matrix.Compose = function (scale, rotation, translation) {
  1865. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1866. var rotationMatrix = Matrix.Identity();
  1867. rotation.toRotationMatrix(rotationMatrix);
  1868. result = result.multiply(rotationMatrix);
  1869. result.setTranslation(translation);
  1870. return result;
  1871. };
  1872. Matrix.Identity = function () {
  1873. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1874. };
  1875. Matrix.IdentityToRef = function (result) {
  1876. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1877. };
  1878. Matrix.Zero = function () {
  1879. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1880. };
  1881. Matrix.RotationX = function (angle) {
  1882. var result = new Matrix();
  1883. Matrix.RotationXToRef(angle, result);
  1884. return result;
  1885. };
  1886. Matrix.Invert = function (source) {
  1887. var result = new Matrix();
  1888. source.invertToRef(result);
  1889. return result;
  1890. };
  1891. Matrix.RotationXToRef = function (angle, result) {
  1892. var s = Math.sin(angle);
  1893. var c = Math.cos(angle);
  1894. result.m[0] = 1.0;
  1895. result.m[15] = 1.0;
  1896. result.m[5] = c;
  1897. result.m[10] = c;
  1898. result.m[9] = -s;
  1899. result.m[6] = s;
  1900. result.m[1] = 0;
  1901. result.m[2] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[7] = 0;
  1905. result.m[8] = 0;
  1906. result.m[11] = 0;
  1907. result.m[12] = 0;
  1908. result.m[13] = 0;
  1909. result.m[14] = 0;
  1910. };
  1911. Matrix.RotationY = function (angle) {
  1912. var result = new Matrix();
  1913. Matrix.RotationYToRef(angle, result);
  1914. return result;
  1915. };
  1916. Matrix.RotationYToRef = function (angle, result) {
  1917. var s = Math.sin(angle);
  1918. var c = Math.cos(angle);
  1919. result.m[5] = 1.0;
  1920. result.m[15] = 1.0;
  1921. result.m[0] = c;
  1922. result.m[2] = -s;
  1923. result.m[8] = s;
  1924. result.m[10] = c;
  1925. result.m[1] = 0;
  1926. result.m[3] = 0;
  1927. result.m[4] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[9] = 0;
  1931. result.m[11] = 0;
  1932. result.m[12] = 0;
  1933. result.m[13] = 0;
  1934. result.m[14] = 0;
  1935. };
  1936. Matrix.RotationZ = function (angle) {
  1937. var result = new Matrix();
  1938. Matrix.RotationZToRef(angle, result);
  1939. return result;
  1940. };
  1941. Matrix.RotationZToRef = function (angle, result) {
  1942. var s = Math.sin(angle);
  1943. var c = Math.cos(angle);
  1944. result.m[10] = 1.0;
  1945. result.m[15] = 1.0;
  1946. result.m[0] = c;
  1947. result.m[1] = s;
  1948. result.m[4] = -s;
  1949. result.m[5] = c;
  1950. result.m[2] = 0;
  1951. result.m[3] = 0;
  1952. result.m[6] = 0;
  1953. result.m[7] = 0;
  1954. result.m[8] = 0;
  1955. result.m[9] = 0;
  1956. result.m[11] = 0;
  1957. result.m[12] = 0;
  1958. result.m[13] = 0;
  1959. result.m[14] = 0;
  1960. };
  1961. Matrix.RotationAxis = function (axis, angle) {
  1962. var result = Matrix.Zero();
  1963. Matrix.RotationAxisToRef(axis, angle, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1967. var s = Math.sin(-angle);
  1968. var c = Math.cos(-angle);
  1969. var c1 = 1 - c;
  1970. axis.normalize();
  1971. result.m[0] = (axis.x * axis.x) * c1 + c;
  1972. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1973. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1974. result.m[3] = 0.0;
  1975. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1976. result.m[5] = (axis.y * axis.y) * c1 + c;
  1977. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1978. result.m[7] = 0.0;
  1979. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1980. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1981. result.m[10] = (axis.z * axis.z) * c1 + c;
  1982. result.m[11] = 0.0;
  1983. result.m[15] = 1.0;
  1984. };
  1985. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1986. var result = new Matrix();
  1987. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1988. return result;
  1989. };
  1990. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1991. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1992. this._tempQuaternion.toRotationMatrix(result);
  1993. };
  1994. Matrix.Scaling = function (x, y, z) {
  1995. var result = Matrix.Zero();
  1996. Matrix.ScalingToRef(x, y, z, result);
  1997. return result;
  1998. };
  1999. Matrix.ScalingToRef = function (x, y, z, result) {
  2000. result.m[0] = x;
  2001. result.m[1] = 0;
  2002. result.m[2] = 0;
  2003. result.m[3] = 0;
  2004. result.m[4] = 0;
  2005. result.m[5] = y;
  2006. result.m[6] = 0;
  2007. result.m[7] = 0;
  2008. result.m[8] = 0;
  2009. result.m[9] = 0;
  2010. result.m[10] = z;
  2011. result.m[11] = 0;
  2012. result.m[12] = 0;
  2013. result.m[13] = 0;
  2014. result.m[14] = 0;
  2015. result.m[15] = 1.0;
  2016. };
  2017. Matrix.Translation = function (x, y, z) {
  2018. var result = Matrix.Identity();
  2019. Matrix.TranslationToRef(x, y, z, result);
  2020. return result;
  2021. };
  2022. Matrix.TranslationToRef = function (x, y, z, result) {
  2023. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2024. };
  2025. Matrix.Lerp = function (startValue, endValue, gradient) {
  2026. var startScale = new Vector3(0, 0, 0);
  2027. var startRotation = new Quaternion();
  2028. var startTranslation = new Vector3(0, 0, 0);
  2029. startValue.decompose(startScale, startRotation, startTranslation);
  2030. var endScale = new Vector3(0, 0, 0);
  2031. var endRotation = new Quaternion();
  2032. var endTranslation = new Vector3(0, 0, 0);
  2033. endValue.decompose(endScale, endRotation, endTranslation);
  2034. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2035. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2036. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2037. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2038. };
  2039. Matrix.LookAtLH = function (eye, target, up) {
  2040. var result = Matrix.Zero();
  2041. Matrix.LookAtLHToRef(eye, target, up, result);
  2042. return result;
  2043. };
  2044. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2045. // Z axis
  2046. target.subtractToRef(eye, this._zAxis);
  2047. this._zAxis.normalize();
  2048. // X axis
  2049. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2050. if (this._xAxis.lengthSquared() === 0) {
  2051. this._xAxis.x = 1.0;
  2052. }
  2053. else {
  2054. this._xAxis.normalize();
  2055. }
  2056. // Y axis
  2057. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2058. this._yAxis.normalize();
  2059. // Eye angles
  2060. var ex = -Vector3.Dot(this._xAxis, eye);
  2061. var ey = -Vector3.Dot(this._yAxis, eye);
  2062. var ez = -Vector3.Dot(this._zAxis, eye);
  2063. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2064. };
  2065. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2066. var matrix = Matrix.Zero();
  2067. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2068. return matrix;
  2069. };
  2070. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2071. var hw = 2.0 / width;
  2072. var hh = 2.0 / height;
  2073. var id = 1.0 / (zfar - znear);
  2074. var nid = znear / (znear - zfar);
  2075. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2076. };
  2077. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2078. var matrix = Matrix.Zero();
  2079. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2080. return matrix;
  2081. };
  2082. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2083. result.m[0] = 2.0 / (right - left);
  2084. result.m[1] = result.m[2] = result.m[3] = 0;
  2085. result.m[5] = 2.0 / (top - bottom);
  2086. result.m[4] = result.m[6] = result.m[7] = 0;
  2087. result.m[10] = -1.0 / (znear - zfar);
  2088. result.m[8] = result.m[9] = result.m[11] = 0;
  2089. result.m[12] = (left + right) / (left - right);
  2090. result.m[13] = (top + bottom) / (bottom - top);
  2091. result.m[14] = znear / (znear - zfar);
  2092. result.m[15] = 1.0;
  2093. };
  2094. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2095. var matrix = Matrix.Zero();
  2096. matrix.m[0] = (2.0 * znear) / width;
  2097. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2098. matrix.m[5] = (2.0 * znear) / height;
  2099. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2100. matrix.m[10] = -zfar / (znear - zfar);
  2101. matrix.m[8] = matrix.m[9] = 0.0;
  2102. matrix.m[11] = 1.0;
  2103. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2104. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2105. return matrix;
  2106. };
  2107. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2108. var matrix = Matrix.Zero();
  2109. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2110. return matrix;
  2111. };
  2112. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2113. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2114. var tan = 1.0 / (Math.tan(fov * 0.5));
  2115. if (isVerticalFovFixed) {
  2116. result.m[0] = tan / aspect;
  2117. }
  2118. else {
  2119. result.m[0] = tan;
  2120. }
  2121. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2122. if (isVerticalFovFixed) {
  2123. result.m[5] = tan;
  2124. }
  2125. else {
  2126. result.m[5] = tan * aspect;
  2127. }
  2128. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2129. result.m[8] = result.m[9] = 0.0;
  2130. result.m[10] = -zfar / (znear - zfar);
  2131. result.m[11] = 1.0;
  2132. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2133. result.m[14] = (znear * zfar) / (znear - zfar);
  2134. };
  2135. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2136. var cw = viewport.width;
  2137. var ch = viewport.height;
  2138. var cx = viewport.x;
  2139. var cy = viewport.y;
  2140. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2141. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2142. };
  2143. Matrix.GetAsMatrix2x2 = function (matrix) {
  2144. return new Float32Array([
  2145. matrix.m[0], matrix.m[1],
  2146. matrix.m[4], matrix.m[5]
  2147. ]);
  2148. };
  2149. Matrix.GetAsMatrix3x3 = function (matrix) {
  2150. return new Float32Array([
  2151. matrix.m[0], matrix.m[1], matrix.m[2],
  2152. matrix.m[4], matrix.m[5], matrix.m[6],
  2153. matrix.m[8], matrix.m[9], matrix.m[10]
  2154. ]);
  2155. };
  2156. Matrix.Transpose = function (matrix) {
  2157. var result = new Matrix();
  2158. result.m[0] = matrix.m[0];
  2159. result.m[1] = matrix.m[4];
  2160. result.m[2] = matrix.m[8];
  2161. result.m[3] = matrix.m[12];
  2162. result.m[4] = matrix.m[1];
  2163. result.m[5] = matrix.m[5];
  2164. result.m[6] = matrix.m[9];
  2165. result.m[7] = matrix.m[13];
  2166. result.m[8] = matrix.m[2];
  2167. result.m[9] = matrix.m[6];
  2168. result.m[10] = matrix.m[10];
  2169. result.m[11] = matrix.m[14];
  2170. result.m[12] = matrix.m[3];
  2171. result.m[13] = matrix.m[7];
  2172. result.m[14] = matrix.m[11];
  2173. result.m[15] = matrix.m[15];
  2174. return result;
  2175. };
  2176. Matrix.Reflection = function (plane) {
  2177. var matrix = new Matrix();
  2178. Matrix.ReflectionToRef(plane, matrix);
  2179. return matrix;
  2180. };
  2181. Matrix.ReflectionToRef = function (plane, result) {
  2182. plane.normalize();
  2183. var x = plane.normal.x;
  2184. var y = plane.normal.y;
  2185. var z = plane.normal.z;
  2186. var temp = -2 * x;
  2187. var temp2 = -2 * y;
  2188. var temp3 = -2 * z;
  2189. result.m[0] = (temp * x) + 1;
  2190. result.m[1] = temp2 * x;
  2191. result.m[2] = temp3 * x;
  2192. result.m[3] = 0.0;
  2193. result.m[4] = temp * y;
  2194. result.m[5] = (temp2 * y) + 1;
  2195. result.m[6] = temp3 * y;
  2196. result.m[7] = 0.0;
  2197. result.m[8] = temp * z;
  2198. result.m[9] = temp2 * z;
  2199. result.m[10] = (temp3 * z) + 1;
  2200. result.m[11] = 0.0;
  2201. result.m[12] = temp * plane.d;
  2202. result.m[13] = temp2 * plane.d;
  2203. result.m[14] = temp3 * plane.d;
  2204. result.m[15] = 1.0;
  2205. };
  2206. Matrix._tempQuaternion = new Quaternion();
  2207. Matrix._xAxis = Vector3.Zero();
  2208. Matrix._yAxis = Vector3.Zero();
  2209. Matrix._zAxis = Vector3.Zero();
  2210. return Matrix;
  2211. })();
  2212. BABYLON.Matrix = Matrix;
  2213. var Plane = (function () {
  2214. function Plane(a, b, c, d) {
  2215. this.normal = new Vector3(a, b, c);
  2216. this.d = d;
  2217. }
  2218. Plane.prototype.asArray = function () {
  2219. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2220. };
  2221. // Methods
  2222. Plane.prototype.clone = function () {
  2223. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2224. };
  2225. Plane.prototype.normalize = function () {
  2226. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2227. var magnitude = 0;
  2228. if (norm !== 0) {
  2229. magnitude = 1.0 / norm;
  2230. }
  2231. this.normal.x *= magnitude;
  2232. this.normal.y *= magnitude;
  2233. this.normal.z *= magnitude;
  2234. this.d *= magnitude;
  2235. return this;
  2236. };
  2237. Plane.prototype.transform = function (transformation) {
  2238. var transposedMatrix = Matrix.Transpose(transformation);
  2239. var x = this.normal.x;
  2240. var y = this.normal.y;
  2241. var z = this.normal.z;
  2242. var d = this.d;
  2243. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2244. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2245. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2246. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2247. return new Plane(normalX, normalY, normalZ, finalD);
  2248. };
  2249. Plane.prototype.dotCoordinate = function (point) {
  2250. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2251. };
  2252. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2253. var x1 = point2.x - point1.x;
  2254. var y1 = point2.y - point1.y;
  2255. var z1 = point2.z - point1.z;
  2256. var x2 = point3.x - point1.x;
  2257. var y2 = point3.y - point1.y;
  2258. var z2 = point3.z - point1.z;
  2259. var yz = (y1 * z2) - (z1 * y2);
  2260. var xz = (z1 * x2) - (x1 * z2);
  2261. var xy = (x1 * y2) - (y1 * x2);
  2262. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2263. var invPyth;
  2264. if (pyth !== 0) {
  2265. invPyth = 1.0 / pyth;
  2266. }
  2267. else {
  2268. invPyth = 0;
  2269. }
  2270. this.normal.x = yz * invPyth;
  2271. this.normal.y = xz * invPyth;
  2272. this.normal.z = xy * invPyth;
  2273. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2274. return this;
  2275. };
  2276. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2277. var dot = Vector3.Dot(this.normal, direction);
  2278. return (dot <= epsilon);
  2279. };
  2280. Plane.prototype.signedDistanceTo = function (point) {
  2281. return Vector3.Dot(point, this.normal) + this.d;
  2282. };
  2283. // Statics
  2284. Plane.FromArray = function (array) {
  2285. return new Plane(array[0], array[1], array[2], array[3]);
  2286. };
  2287. Plane.FromPoints = function (point1, point2, point3) {
  2288. var result = new Plane(0, 0, 0, 0);
  2289. result.copyFromPoints(point1, point2, point3);
  2290. return result;
  2291. };
  2292. Plane.FromPositionAndNormal = function (origin, normal) {
  2293. var result = new Plane(0, 0, 0, 0);
  2294. normal.normalize();
  2295. result.normal = normal;
  2296. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2297. return result;
  2298. };
  2299. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2300. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2301. return Vector3.Dot(point, normal) + d;
  2302. };
  2303. return Plane;
  2304. })();
  2305. BABYLON.Plane = Plane;
  2306. var Viewport = (function () {
  2307. function Viewport(x, y, width, height) {
  2308. this.x = x;
  2309. this.y = y;
  2310. this.width = width;
  2311. this.height = height;
  2312. }
  2313. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2314. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2315. };
  2316. return Viewport;
  2317. })();
  2318. BABYLON.Viewport = Viewport;
  2319. var Frustum = (function () {
  2320. function Frustum() {
  2321. }
  2322. Frustum.GetPlanes = function (transform) {
  2323. var frustumPlanes = [];
  2324. for (var index = 0; index < 6; index++) {
  2325. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2326. }
  2327. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2328. return frustumPlanes;
  2329. };
  2330. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2331. // Near
  2332. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2333. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2334. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2335. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2336. frustumPlanes[0].normalize();
  2337. // Far
  2338. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2339. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2340. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2341. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2342. frustumPlanes[1].normalize();
  2343. // Left
  2344. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2345. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2346. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2347. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2348. frustumPlanes[2].normalize();
  2349. // Right
  2350. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2351. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2352. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2353. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2354. frustumPlanes[3].normalize();
  2355. // Top
  2356. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2357. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2358. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2359. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2360. frustumPlanes[4].normalize();
  2361. // Bottom
  2362. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2363. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2364. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2365. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2366. frustumPlanes[5].normalize();
  2367. };
  2368. return Frustum;
  2369. })();
  2370. BABYLON.Frustum = Frustum;
  2371. (function (Space) {
  2372. Space[Space["LOCAL"] = 0] = "LOCAL";
  2373. Space[Space["WORLD"] = 1] = "WORLD";
  2374. })(BABYLON.Space || (BABYLON.Space = {}));
  2375. var Space = BABYLON.Space;
  2376. var Axis = (function () {
  2377. function Axis() {
  2378. }
  2379. Axis.X = new Vector3(1, 0, 0);
  2380. Axis.Y = new Vector3(0, 1, 0);
  2381. Axis.Z = new Vector3(0, 0, 1);
  2382. return Axis;
  2383. })();
  2384. BABYLON.Axis = Axis;
  2385. ;
  2386. var BezierCurve = (function () {
  2387. function BezierCurve() {
  2388. }
  2389. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2390. // Extract X (which is equal to time here)
  2391. var f0 = 1 - 3 * x2 + 3 * x1;
  2392. var f1 = 3 * x2 - 6 * x1;
  2393. var f2 = 3 * x1;
  2394. var refinedT = t;
  2395. for (var i = 0; i < 5; i++) {
  2396. var refinedT2 = refinedT * refinedT;
  2397. var refinedT3 = refinedT2 * refinedT;
  2398. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2399. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2400. refinedT -= (x - t) * slope;
  2401. refinedT = Math.min(1, Math.max(0, refinedT));
  2402. }
  2403. // Resolve cubic bezier for the given x
  2404. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2405. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2406. Math.pow(refinedT, 3);
  2407. };
  2408. return BezierCurve;
  2409. })();
  2410. BABYLON.BezierCurve = BezierCurve;
  2411. (function (Orientation) {
  2412. Orientation[Orientation["CW"] = 0] = "CW";
  2413. Orientation[Orientation["CCW"] = 1] = "CCW";
  2414. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2415. var Orientation = BABYLON.Orientation;
  2416. var Angle = (function () {
  2417. function Angle(radians) {
  2418. var _this = this;
  2419. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2420. this.radians = function () { return _this._radians; };
  2421. this._radians = radians;
  2422. if (this._radians < 0)
  2423. this._radians += (2 * Math.PI);
  2424. }
  2425. Angle.BetweenTwoPoints = function (a, b) {
  2426. var delta = b.subtract(a);
  2427. var theta = Math.atan2(delta.y, delta.x);
  2428. return new Angle(theta);
  2429. };
  2430. Angle.FromRadians = function (radians) {
  2431. return new Angle(radians);
  2432. };
  2433. Angle.FromDegrees = function (degrees) {
  2434. return new Angle(degrees * Math.PI / 180);
  2435. };
  2436. return Angle;
  2437. })();
  2438. BABYLON.Angle = Angle;
  2439. var Arc2 = (function () {
  2440. function Arc2(startPoint, midPoint, endPoint) {
  2441. this.startPoint = startPoint;
  2442. this.midPoint = midPoint;
  2443. this.endPoint = endPoint;
  2444. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2445. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2446. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2447. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2448. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2449. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2450. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2451. var a1 = this.startAngle.degrees();
  2452. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2453. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2454. // angles correction
  2455. if (a2 - a1 > +180.0)
  2456. a2 -= 360.0;
  2457. if (a2 - a1 < -180.0)
  2458. a2 += 360.0;
  2459. if (a3 - a2 > +180.0)
  2460. a3 -= 360.0;
  2461. if (a3 - a2 < -180.0)
  2462. a3 += 360.0;
  2463. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2464. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2465. }
  2466. return Arc2;
  2467. })();
  2468. BABYLON.Arc2 = Arc2;
  2469. var Path2 = (function () {
  2470. function Path2(x, y) {
  2471. this._points = new Array();
  2472. this._length = 0;
  2473. this.closed = false;
  2474. this._points.push(new Vector2(x, y));
  2475. }
  2476. Path2.prototype.addLineTo = function (x, y) {
  2477. if (closed) {
  2478. //Tools.Error("cannot add lines to closed paths");
  2479. return this;
  2480. }
  2481. var newPoint = new Vector2(x, y);
  2482. var previousPoint = this._points[this._points.length - 1];
  2483. this._points.push(newPoint);
  2484. this._length += newPoint.subtract(previousPoint).length();
  2485. return this;
  2486. };
  2487. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2488. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2489. if (closed) {
  2490. //Tools.Error("cannot add arcs to closed paths");
  2491. return this;
  2492. }
  2493. var startPoint = this._points[this._points.length - 1];
  2494. var midPoint = new Vector2(midX, midY);
  2495. var endPoint = new Vector2(endX, endY);
  2496. var arc = new Arc2(startPoint, midPoint, endPoint);
  2497. var increment = arc.angle.radians() / numberOfSegments;
  2498. if (arc.orientation === Orientation.CW)
  2499. increment *= -1;
  2500. var currentAngle = arc.startAngle.radians() + increment;
  2501. for (var i = 0; i < numberOfSegments; i++) {
  2502. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2503. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2504. this.addLineTo(x, y);
  2505. currentAngle += increment;
  2506. }
  2507. return this;
  2508. };
  2509. Path2.prototype.close = function () {
  2510. this.closed = true;
  2511. return this;
  2512. };
  2513. Path2.prototype.length = function () {
  2514. var result = this._length;
  2515. if (!this.closed) {
  2516. var lastPoint = this._points[this._points.length - 1];
  2517. var firstPoint = this._points[0];
  2518. result += (firstPoint.subtract(lastPoint).length());
  2519. }
  2520. return result;
  2521. };
  2522. Path2.prototype.getPoints = function () {
  2523. return this._points;
  2524. };
  2525. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2526. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2527. //Tools.Error("normalized length position should be between 0 and 1.");
  2528. return Vector2.Zero();
  2529. }
  2530. var lengthPosition = normalizedLengthPosition * this.length();
  2531. var previousOffset = 0;
  2532. for (var i = 0; i < this._points.length; i++) {
  2533. var j = (i + 1) % this._points.length;
  2534. var a = this._points[i];
  2535. var b = this._points[j];
  2536. var bToA = b.subtract(a);
  2537. var nextOffset = (bToA.length() + previousOffset);
  2538. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2539. var dir = bToA.normalize();
  2540. var localOffset = lengthPosition - previousOffset;
  2541. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2542. }
  2543. previousOffset = nextOffset;
  2544. }
  2545. //Tools.Error("internal error");
  2546. return Vector2.Zero();
  2547. };
  2548. Path2.StartingAt = function (x, y) {
  2549. return new Path2(x, y);
  2550. };
  2551. return Path2;
  2552. })();
  2553. BABYLON.Path2 = Path2;
  2554. var Path3D = (function () {
  2555. /**
  2556. * new Path3D(path, normal, raw)
  2557. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2558. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2559. * path : an array of Vector3, the curve axis of the Path3D
  2560. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2561. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2562. */
  2563. function Path3D(path, firstNormal, raw) {
  2564. this.path = path;
  2565. this._curve = new Array();
  2566. this._distances = new Array();
  2567. this._tangents = new Array();
  2568. this._normals = new Array();
  2569. this._binormals = new Array();
  2570. for (var p = 0; p < path.length; p++) {
  2571. this._curve[p] = path[p].clone(); // hard copy
  2572. }
  2573. this._raw = raw || false;
  2574. this._compute(firstNormal);
  2575. }
  2576. /**
  2577. * Returns the Path3D array of successive Vector3 designing its curve.
  2578. */
  2579. Path3D.prototype.getCurve = function () {
  2580. return this._curve;
  2581. };
  2582. /**
  2583. * Returns an array populated with tangent vectors on each Path3D curve point.
  2584. */
  2585. Path3D.prototype.getTangents = function () {
  2586. return this._tangents;
  2587. };
  2588. /**
  2589. * Returns an array populated with normal vectors on each Path3D curve point.
  2590. */
  2591. Path3D.prototype.getNormals = function () {
  2592. return this._normals;
  2593. };
  2594. /**
  2595. * Returns an array populated with binormal vectors on each Path3D curve point.
  2596. */
  2597. Path3D.prototype.getBinormals = function () {
  2598. return this._binormals;
  2599. };
  2600. /**
  2601. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2602. */
  2603. Path3D.prototype.getDistances = function () {
  2604. return this._distances;
  2605. };
  2606. /**
  2607. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2608. * Returns the same object updated.
  2609. */
  2610. Path3D.prototype.update = function (path, firstNormal) {
  2611. for (var p = 0; p < path.length; p++) {
  2612. this._curve[p].x = path[p].x;
  2613. this._curve[p].y = path[p].y;
  2614. this._curve[p].z = path[p].z;
  2615. }
  2616. this._compute(firstNormal);
  2617. return this;
  2618. };
  2619. // private function compute() : computes tangents, normals and binormals
  2620. Path3D.prototype._compute = function (firstNormal) {
  2621. var l = this._curve.length;
  2622. // first and last tangents
  2623. this._tangents[0] = this._getFirstNonNullVector(0);
  2624. if (!this._raw) {
  2625. this._tangents[0].normalize();
  2626. }
  2627. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2628. if (!this._raw) {
  2629. this._tangents[l - 1].normalize();
  2630. }
  2631. // normals and binormals at first point : arbitrary vector with _normalVector()
  2632. var tg0 = this._tangents[0];
  2633. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2634. this._normals[0] = pp0;
  2635. if (!this._raw) {
  2636. this._normals[0].normalize();
  2637. }
  2638. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2639. if (!this._raw) {
  2640. this._binormals[0].normalize();
  2641. }
  2642. this._distances[0] = 0;
  2643. // normals and binormals : next points
  2644. var prev; // previous vector (segment)
  2645. var cur; // current vector (segment)
  2646. var curTang; // current tangent
  2647. // previous normal
  2648. var prevBinor; // previous binormal
  2649. for (var i = 1; i < l; i++) {
  2650. // tangents
  2651. prev = this._getLastNonNullVector(i);
  2652. if (i < l - 1) {
  2653. cur = this._getFirstNonNullVector(i);
  2654. this._tangents[i] = prev.add(cur);
  2655. this._tangents[i].normalize();
  2656. }
  2657. this._distances[i] = this._distances[i - 1] + prev.length();
  2658. // normals and binormals
  2659. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2660. curTang = this._tangents[i];
  2661. prevBinor = this._binormals[i - 1];
  2662. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2663. if (!this._raw) {
  2664. this._normals[i].normalize();
  2665. }
  2666. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2667. if (!this._raw) {
  2668. this._binormals[i].normalize();
  2669. }
  2670. }
  2671. };
  2672. // private function getFirstNonNullVector(index)
  2673. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2674. Path3D.prototype._getFirstNonNullVector = function (index) {
  2675. var i = 1;
  2676. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2677. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2678. i++;
  2679. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2680. }
  2681. return nNVector;
  2682. };
  2683. // private function getLastNonNullVector(index)
  2684. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2685. Path3D.prototype._getLastNonNullVector = function (index) {
  2686. var i = 1;
  2687. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2688. while (nLVector.length() === 0 && index > i + 1) {
  2689. i++;
  2690. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2691. }
  2692. return nLVector;
  2693. };
  2694. // private function normalVector(v0, vt, va) :
  2695. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2696. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2697. Path3D.prototype._normalVector = function (v0, vt, va) {
  2698. var normal0;
  2699. if (va === undefined || va === null) {
  2700. var point;
  2701. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2702. point = new Vector3(0, -1, 0);
  2703. }
  2704. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2705. point = new Vector3(1, 0, 0);
  2706. }
  2707. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2708. point = new Vector3(0, 0, 1);
  2709. }
  2710. normal0 = Vector3.Cross(vt, point);
  2711. }
  2712. else {
  2713. normal0 = Vector3.Cross(vt, va);
  2714. Vector3.CrossToRef(normal0, vt, normal0);
  2715. }
  2716. normal0.normalize();
  2717. return normal0;
  2718. };
  2719. return Path3D;
  2720. })();
  2721. BABYLON.Path3D = Path3D;
  2722. var Curve3 = (function () {
  2723. /**
  2724. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2725. * A Curve3 is designed from a series of successive Vector3.
  2726. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2727. */
  2728. function Curve3(points) {
  2729. this._length = 0;
  2730. this._points = points;
  2731. this._length = this._computeLength(points);
  2732. }
  2733. /**
  2734. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2735. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2736. * @param v1 (Vector3) the control point
  2737. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2738. * @param nbPoints (integer) the wanted number of points in the curve
  2739. */
  2740. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2741. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2742. var bez = new Array();
  2743. var equation = function (t, val0, val1, val2) {
  2744. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2745. return res;
  2746. };
  2747. for (var i = 0; i <= nbPoints; i++) {
  2748. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2749. }
  2750. return new Curve3(bez);
  2751. };
  2752. /**
  2753. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2754. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2755. * @param v1 (Vector3) the first control point
  2756. * @param v2 (Vector3) the second control point
  2757. * @param v3 (Vector3) the end point of the Cubic Bezier
  2758. * @param nbPoints (integer) the wanted number of points in the curve
  2759. */
  2760. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2761. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2762. var bez = new Array();
  2763. var equation = function (t, val0, val1, val2, val3) {
  2764. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2765. return res;
  2766. };
  2767. for (var i = 0; i <= nbPoints; i++) {
  2768. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2769. }
  2770. return new Curve3(bez);
  2771. };
  2772. /**
  2773. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2774. * @param p1 (Vector3) the origin point of the Hermite Spline
  2775. * @param t1 (Vector3) the tangent vector at the origin point
  2776. * @param p2 (Vector3) the end point of the Hermite Spline
  2777. * @param t2 (Vector3) the tangent vector at the end point
  2778. * @param nbPoints (integer) the wanted number of points in the curve
  2779. */
  2780. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2781. var hermite = new Array();
  2782. var step = 1 / nbPoints;
  2783. for (var i = 0; i <= nbPoints; i++) {
  2784. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2785. }
  2786. return new Curve3(hermite);
  2787. };
  2788. /**
  2789. * Returns the Curve3 stored array of successive Vector3
  2790. */
  2791. Curve3.prototype.getPoints = function () {
  2792. return this._points;
  2793. };
  2794. /**
  2795. * Returns the computed length (float) of the curve.
  2796. */
  2797. Curve3.prototype.length = function () {
  2798. return this._length;
  2799. };
  2800. /**
  2801. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2802. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2803. * curveA and curveB keep unchanged.
  2804. */
  2805. Curve3.prototype.continue = function (curve) {
  2806. var lastPoint = this._points[this._points.length - 1];
  2807. var continuedPoints = this._points.slice();
  2808. var curvePoints = curve.getPoints();
  2809. for (var i = 1; i < curvePoints.length; i++) {
  2810. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2811. }
  2812. var continuedCurve = new Curve3(continuedPoints);
  2813. return continuedCurve;
  2814. };
  2815. Curve3.prototype._computeLength = function (path) {
  2816. var l = 0;
  2817. for (var i = 1; i < path.length; i++) {
  2818. l += (path[i].subtract(path[i - 1])).length();
  2819. }
  2820. return l;
  2821. };
  2822. return Curve3;
  2823. })();
  2824. BABYLON.Curve3 = Curve3;
  2825. // SphericalHarmonics
  2826. var SphericalHarmonics = (function () {
  2827. function SphericalHarmonics() {
  2828. this.L00 = Vector3.Zero();
  2829. this.L1_1 = Vector3.Zero();
  2830. this.L10 = Vector3.Zero();
  2831. this.L11 = Vector3.Zero();
  2832. this.L2_2 = Vector3.Zero();
  2833. this.L2_1 = Vector3.Zero();
  2834. this.L20 = Vector3.Zero();
  2835. this.L21 = Vector3.Zero();
  2836. this.L22 = Vector3.Zero();
  2837. }
  2838. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2839. var colorVector = new Vector3(color.r, color.g, color.b);
  2840. var c = colorVector.scale(deltaSolidAngle);
  2841. this.L00 = this.L00.add(c.scale(0.282095));
  2842. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2843. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2844. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2845. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2846. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2847. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2848. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2849. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2850. };
  2851. SphericalHarmonics.prototype.scale = function (scale) {
  2852. this.L00 = this.L00.scale(scale);
  2853. this.L1_1 = this.L1_1.scale(scale);
  2854. this.L10 = this.L10.scale(scale);
  2855. this.L11 = this.L11.scale(scale);
  2856. this.L2_2 = this.L2_2.scale(scale);
  2857. this.L2_1 = this.L2_1.scale(scale);
  2858. this.L20 = this.L20.scale(scale);
  2859. this.L21 = this.L21.scale(scale);
  2860. this.L22 = this.L22.scale(scale);
  2861. };
  2862. return SphericalHarmonics;
  2863. })();
  2864. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2865. // SphericalPolynomial
  2866. var SphericalPolynomial = (function () {
  2867. function SphericalPolynomial() {
  2868. this.x = Vector3.Zero();
  2869. this.y = Vector3.Zero();
  2870. this.z = Vector3.Zero();
  2871. this.xx = Vector3.Zero();
  2872. this.yy = Vector3.Zero();
  2873. this.zz = Vector3.Zero();
  2874. this.xy = Vector3.Zero();
  2875. this.yz = Vector3.Zero();
  2876. this.zx = Vector3.Zero();
  2877. }
  2878. SphericalPolynomial.prototype.addAmbient = function (color) {
  2879. var colorVector = new Vector3(color.r, color.g, color.b);
  2880. this.xx = this.xx.add(colorVector);
  2881. this.yy = this.yy.add(colorVector);
  2882. this.zz = this.zz.add(colorVector);
  2883. };
  2884. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2885. var result = new SphericalPolynomial();
  2886. result.x = harmonics.L11.scale(1.02333);
  2887. result.y = harmonics.L1_1.scale(1.02333);
  2888. result.z = harmonics.L10.scale(1.02333);
  2889. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2890. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2891. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2892. result.yz = harmonics.L2_1.scale(0.858086);
  2893. result.zx = harmonics.L21.scale(0.858086);
  2894. result.xy = harmonics.L2_2.scale(0.858086);
  2895. return result;
  2896. };
  2897. return SphericalPolynomial;
  2898. })();
  2899. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2900. // Vertex formats
  2901. var PositionNormalVertex = (function () {
  2902. function PositionNormalVertex(position, normal) {
  2903. if (position === void 0) { position = Vector3.Zero(); }
  2904. if (normal === void 0) { normal = Vector3.Up(); }
  2905. this.position = position;
  2906. this.normal = normal;
  2907. }
  2908. PositionNormalVertex.prototype.clone = function () {
  2909. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2910. };
  2911. return PositionNormalVertex;
  2912. })();
  2913. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2914. var PositionNormalTextureVertex = (function () {
  2915. function PositionNormalTextureVertex(position, normal, uv) {
  2916. if (position === void 0) { position = Vector3.Zero(); }
  2917. if (normal === void 0) { normal = Vector3.Up(); }
  2918. if (uv === void 0) { uv = Vector2.Zero(); }
  2919. this.position = position;
  2920. this.normal = normal;
  2921. this.uv = uv;
  2922. }
  2923. PositionNormalTextureVertex.prototype.clone = function () {
  2924. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2925. };
  2926. return PositionNormalTextureVertex;
  2927. })();
  2928. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2929. // Temporary pre-allocated objects for engine internal use
  2930. // usage in any internal function :
  2931. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2932. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2933. var Tmp = (function () {
  2934. function Tmp() {
  2935. }
  2936. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2937. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2938. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2939. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2940. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2941. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2942. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2943. Matrix.Zero(), Matrix.Zero(),
  2944. Matrix.Zero(), Matrix.Zero(),
  2945. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2946. return Tmp;
  2947. })();
  2948. BABYLON.Tmp = Tmp;
  2949. })(BABYLON || (BABYLON = {}));
  2950. var BABYLON;
  2951. (function (BABYLON) {
  2952. function generateSerializableMember(type, sourceName) {
  2953. return function (target, propertyKey) {
  2954. if (!target.__serializableMembers) {
  2955. target.__serializableMembers = {};
  2956. }
  2957. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2958. };
  2959. }
  2960. function serialize(sourceName) {
  2961. return generateSerializableMember(0, sourceName); // value member
  2962. }
  2963. BABYLON.serialize = serialize;
  2964. function serializeAsTexture(sourceName) {
  2965. return generateSerializableMember(1, sourceName); // texture member
  2966. }
  2967. BABYLON.serializeAsTexture = serializeAsTexture;
  2968. function serializeAsColor3(sourceName) {
  2969. return generateSerializableMember(2, sourceName); // color3 member
  2970. }
  2971. BABYLON.serializeAsColor3 = serializeAsColor3;
  2972. function serializeAsFresnelParameters(sourceName) {
  2973. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2974. }
  2975. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2976. function serializeAsVector2(sourceName) {
  2977. return generateSerializableMember(4, sourceName); // vector2 member
  2978. }
  2979. BABYLON.serializeAsVector2 = serializeAsVector2;
  2980. function serializeAsVector3(sourceName) {
  2981. return generateSerializableMember(5, sourceName); // vector3 member
  2982. }
  2983. BABYLON.serializeAsVector3 = serializeAsVector3;
  2984. function serializeAsMeshReference(sourceName) {
  2985. return generateSerializableMember(6, sourceName); // mesh reference member
  2986. }
  2987. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2988. var SerializationHelper = (function () {
  2989. function SerializationHelper() {
  2990. }
  2991. SerializationHelper.Serialize = function (entity, serializationObject) {
  2992. if (!serializationObject) {
  2993. serializationObject = {};
  2994. }
  2995. // Tags
  2996. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2997. // Properties
  2998. for (var property in entity.__serializableMembers) {
  2999. var propertyDescriptor = entity.__serializableMembers[property];
  3000. var targetPropertyName = propertyDescriptor.sourceName || property;
  3001. var propertyType = propertyDescriptor.type;
  3002. var sourceProperty = entity[property];
  3003. if (sourceProperty !== undefined && sourceProperty !== null) {
  3004. switch (propertyType) {
  3005. case 0:
  3006. serializationObject[targetPropertyName] = sourceProperty;
  3007. break;
  3008. case 1:
  3009. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3010. break;
  3011. case 2:
  3012. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3013. break;
  3014. case 3:
  3015. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3016. break;
  3017. case 4:
  3018. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3019. break;
  3020. case 5:
  3021. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3022. break;
  3023. case 6:
  3024. serializationObject[targetPropertyName] = sourceProperty.id;
  3025. break;
  3026. }
  3027. }
  3028. }
  3029. return serializationObject;
  3030. };
  3031. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3032. var destination = creationFunction();
  3033. // Tags
  3034. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3035. // Properties
  3036. for (var property in destination.__serializableMembers) {
  3037. var propertyDescriptor = destination.__serializableMembers[property];
  3038. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3039. var propertyType = propertyDescriptor.type;
  3040. if (sourceProperty !== undefined && sourceProperty !== null) {
  3041. switch (propertyType) {
  3042. case 0:
  3043. destination[property] = sourceProperty;
  3044. break;
  3045. case 1:
  3046. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3047. break;
  3048. case 2:
  3049. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3050. break;
  3051. case 3:
  3052. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3053. break;
  3054. case 4:
  3055. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3056. break;
  3057. case 5:
  3058. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3059. break;
  3060. case 6:
  3061. destination[property] = scene.getLastMeshByID(sourceProperty);
  3062. break;
  3063. }
  3064. }
  3065. }
  3066. return destination;
  3067. };
  3068. SerializationHelper.Clone = function (creationFunction, source) {
  3069. var destination = creationFunction();
  3070. // Tags
  3071. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3072. // Properties
  3073. for (var property in destination.__serializableMembers) {
  3074. var propertyDescriptor = destination.__serializableMembers[property];
  3075. var sourceProperty = source[property];
  3076. var propertyType = propertyDescriptor.type;
  3077. if (sourceProperty !== undefined && sourceProperty !== null) {
  3078. switch (propertyType) {
  3079. case 0: // Value
  3080. case 6:
  3081. destination[property] = sourceProperty;
  3082. break;
  3083. case 1: // Texture
  3084. case 2: // Color3
  3085. case 3: // FresnelParameters
  3086. case 4: // Vector2
  3087. case 5:
  3088. destination[property] = sourceProperty.clone();
  3089. break;
  3090. }
  3091. }
  3092. }
  3093. return destination;
  3094. };
  3095. return SerializationHelper;
  3096. })();
  3097. BABYLON.SerializationHelper = SerializationHelper;
  3098. })(BABYLON || (BABYLON = {}));
  3099. var BABYLON;
  3100. (function (BABYLON) {
  3101. /**
  3102. * A class serves as a medium between the observable and its observers
  3103. */
  3104. var EventState = (function () {
  3105. /**
  3106. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3107. */
  3108. function EventState(skipNextObservers) {
  3109. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3110. this.skipNextObservers = skipNextObservers;
  3111. }
  3112. return EventState;
  3113. })();
  3114. BABYLON.EventState = EventState;
  3115. var Observer = (function () {
  3116. function Observer(callback, mask) {
  3117. this.callback = callback;
  3118. this.mask = mask;
  3119. }
  3120. return Observer;
  3121. })();
  3122. BABYLON.Observer = Observer;
  3123. var Observable = (function () {
  3124. function Observable() {
  3125. this._observers = new Array();
  3126. }
  3127. /**
  3128. * Create a new Observer with the specified callback
  3129. * @param callback the callback that will be executed for that Observer
  3130. * @param mash the mask used to filter observers
  3131. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3132. */
  3133. Observable.prototype.add = function (callback, mask, insertFirst) {
  3134. if (mask === void 0) { mask = -1; }
  3135. if (insertFirst === void 0) { insertFirst = false; }
  3136. if (!callback) {
  3137. return null;
  3138. }
  3139. var observer = new Observer(callback, mask);
  3140. if (insertFirst) {
  3141. this._observers.unshift(observer);
  3142. }
  3143. else {
  3144. this._observers.push(observer);
  3145. }
  3146. return observer;
  3147. };
  3148. /**
  3149. * Remove an Observer from the Observable object
  3150. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3151. */
  3152. Observable.prototype.remove = function (observer) {
  3153. var index = this._observers.indexOf(observer);
  3154. if (index !== -1) {
  3155. this._observers.splice(index, 1);
  3156. return true;
  3157. }
  3158. return false;
  3159. };
  3160. /**
  3161. * Remove a callback from the Observable object
  3162. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3163. */
  3164. Observable.prototype.removeCallback = function (callback) {
  3165. for (var index = 0; index < this._observers.length; index++) {
  3166. if (this._observers[index].callback === callback) {
  3167. this._observers.splice(index, 1);
  3168. return true;
  3169. }
  3170. }
  3171. return false;
  3172. };
  3173. /**
  3174. * Notify all Observers by calling their respective callback with the given data
  3175. * @param eventData
  3176. * @param mask
  3177. */
  3178. Observable.prototype.notifyObservers = function (eventData, mask) {
  3179. if (mask === void 0) { mask = -1; }
  3180. var state = new EventState();
  3181. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3182. var obs = _a[_i];
  3183. if (obs.mask & mask) {
  3184. obs.callback(eventData, state);
  3185. }
  3186. if (state.skipNextObservers) {
  3187. break;
  3188. }
  3189. }
  3190. };
  3191. /**
  3192. * return true is the Observable has at least one Observer registered
  3193. */
  3194. Observable.prototype.hasObservers = function () {
  3195. return this._observers.length > 0;
  3196. };
  3197. /**
  3198. * Clear the list of observers
  3199. */
  3200. Observable.prototype.clear = function () {
  3201. this._observers = new Array();
  3202. };
  3203. /**
  3204. * Clone the current observable
  3205. */
  3206. Observable.prototype.clone = function () {
  3207. var result = new Observable();
  3208. result._observers = this._observers.slice(0);
  3209. return result;
  3210. };
  3211. return Observable;
  3212. })();
  3213. BABYLON.Observable = Observable;
  3214. })(BABYLON || (BABYLON = {}));
  3215. var BABYLON;
  3216. (function (BABYLON) {
  3217. var Database = (function () {
  3218. function Database(urlToScene, callbackManifestChecked) {
  3219. // Handling various flavors of prefixed version of IndexedDB
  3220. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3221. this.callbackManifestChecked = callbackManifestChecked;
  3222. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3223. this.db = null;
  3224. this.enableSceneOffline = false;
  3225. this.enableTexturesOffline = false;
  3226. this.manifestVersionFound = 0;
  3227. this.mustUpdateRessources = false;
  3228. this.hasReachedQuota = false;
  3229. if (!Database.IDBStorageEnabled) {
  3230. this.callbackManifestChecked(true);
  3231. }
  3232. else {
  3233. this.checkManifestFile();
  3234. }
  3235. }
  3236. Database.prototype.checkManifestFile = function () {
  3237. var _this = this;
  3238. function noManifestFile() {
  3239. that.enableSceneOffline = false;
  3240. that.enableTexturesOffline = false;
  3241. that.callbackManifestChecked(false);
  3242. }
  3243. var that = this;
  3244. var timeStampUsed = false;
  3245. var manifestURL = this.currentSceneUrl + ".manifest";
  3246. var xhr = new XMLHttpRequest();
  3247. if (navigator.onLine) {
  3248. // Adding a timestamp to by-pass browsers' cache
  3249. timeStampUsed = true;
  3250. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3251. }
  3252. xhr.open("GET", manifestURL, true);
  3253. xhr.addEventListener("load", function () {
  3254. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3255. try {
  3256. var manifestFile = JSON.parse(xhr.response);
  3257. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3258. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3259. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3260. _this.manifestVersionFound = manifestFile.version;
  3261. }
  3262. if (_this.callbackManifestChecked) {
  3263. _this.callbackManifestChecked(true);
  3264. }
  3265. }
  3266. catch (ex) {
  3267. noManifestFile();
  3268. }
  3269. }
  3270. else {
  3271. noManifestFile();
  3272. }
  3273. }, false);
  3274. xhr.addEventListener("error", function (event) {
  3275. if (timeStampUsed) {
  3276. timeStampUsed = false;
  3277. // Let's retry without the timeStamp
  3278. // It could fail when coupled with HTML5 Offline API
  3279. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3280. xhr.open("GET", retryManifestURL, true);
  3281. xhr.send();
  3282. }
  3283. else {
  3284. noManifestFile();
  3285. }
  3286. }, false);
  3287. try {
  3288. xhr.send();
  3289. }
  3290. catch (ex) {
  3291. BABYLON.Tools.Error("Error on XHR send request.");
  3292. that.callbackManifestChecked(false);
  3293. }
  3294. };
  3295. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3296. var _this = this;
  3297. function handleError() {
  3298. that.isSupported = false;
  3299. if (errorCallback)
  3300. errorCallback();
  3301. }
  3302. var that = this;
  3303. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3304. // Your browser doesn't support IndexedDB
  3305. this.isSupported = false;
  3306. if (errorCallback)
  3307. errorCallback();
  3308. }
  3309. else {
  3310. // If the DB hasn't been opened or created yet
  3311. if (!this.db) {
  3312. this.hasReachedQuota = false;
  3313. this.isSupported = true;
  3314. var request = this.idbFactory.open("babylonjs", 1);
  3315. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3316. request.onerror = function (event) {
  3317. handleError();
  3318. };
  3319. // executes when a version change transaction cannot complete due to other active transactions
  3320. request.onblocked = function (event) {
  3321. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3322. handleError();
  3323. };
  3324. // DB has been opened successfully
  3325. request.onsuccess = function (event) {
  3326. _this.db = request.result;
  3327. successCallback();
  3328. };
  3329. // Initialization of the DB. Creating Scenes & Textures stores
  3330. request.onupgradeneeded = function (event) {
  3331. _this.db = (event.target).result;
  3332. try {
  3333. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3334. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3335. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3336. }
  3337. catch (ex) {
  3338. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3339. handleError();
  3340. }
  3341. };
  3342. }
  3343. else {
  3344. if (successCallback)
  3345. successCallback();
  3346. }
  3347. }
  3348. };
  3349. Database.prototype.loadImageFromDB = function (url, image) {
  3350. var _this = this;
  3351. var completeURL = Database.ReturnFullUrlLocation(url);
  3352. var saveAndLoadImage = function () {
  3353. if (!_this.hasReachedQuota && _this.db !== null) {
  3354. // the texture is not yet in the DB, let's try to save it
  3355. _this._saveImageIntoDBAsync(completeURL, image);
  3356. }
  3357. else {
  3358. image.src = url;
  3359. }
  3360. };
  3361. if (!this.mustUpdateRessources) {
  3362. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3363. }
  3364. else {
  3365. saveAndLoadImage();
  3366. }
  3367. };
  3368. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3369. if (this.isSupported && this.db !== null) {
  3370. var texture;
  3371. var transaction = this.db.transaction(["textures"]);
  3372. transaction.onabort = function (event) {
  3373. image.src = url;
  3374. };
  3375. transaction.oncomplete = function (event) {
  3376. var blobTextureURL;
  3377. if (texture) {
  3378. var URL = window.URL || window.webkitURL;
  3379. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3380. image.onerror = function () {
  3381. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3382. image.src = url;
  3383. };
  3384. image.src = blobTextureURL;
  3385. }
  3386. else {
  3387. notInDBCallback();
  3388. }
  3389. };
  3390. var getRequest = transaction.objectStore("textures").get(url);
  3391. getRequest.onsuccess = function (event) {
  3392. texture = (event.target).result;
  3393. };
  3394. getRequest.onerror = function (event) {
  3395. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3396. image.src = url;
  3397. };
  3398. }
  3399. else {
  3400. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3401. image.src = url;
  3402. }
  3403. };
  3404. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3405. var _this = this;
  3406. if (this.isSupported) {
  3407. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3408. var generateBlobUrl = function () {
  3409. var blobTextureURL;
  3410. if (blob) {
  3411. var URL = window.URL || window.webkitURL;
  3412. try {
  3413. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3414. }
  3415. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3416. catch (ex) {
  3417. blobTextureURL = URL.createObjectURL(blob);
  3418. }
  3419. }
  3420. image.src = blobTextureURL;
  3421. };
  3422. if (Database.IsUASupportingBlobStorage) {
  3423. var xhr = new XMLHttpRequest(), blob;
  3424. xhr.open("GET", url, true);
  3425. xhr.responseType = "blob";
  3426. xhr.addEventListener("load", function () {
  3427. if (xhr.status === 200) {
  3428. // Blob as response (XHR2)
  3429. blob = xhr.response;
  3430. var transaction = _this.db.transaction(["textures"], "readwrite");
  3431. // the transaction could abort because of a QuotaExceededError error
  3432. transaction.onabort = function (event) {
  3433. try {
  3434. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3435. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3436. this.hasReachedQuota = true;
  3437. }
  3438. }
  3439. catch (ex) { }
  3440. generateBlobUrl();
  3441. };
  3442. transaction.oncomplete = function (event) {
  3443. generateBlobUrl();
  3444. };
  3445. var newTexture = { textureUrl: url, data: blob };
  3446. try {
  3447. // Put the blob into the dabase
  3448. var addRequest = transaction.objectStore("textures").put(newTexture);
  3449. addRequest.onsuccess = function (event) {
  3450. };
  3451. addRequest.onerror = function (event) {
  3452. generateBlobUrl();
  3453. };
  3454. }
  3455. catch (ex) {
  3456. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3457. if (ex.code === 25) {
  3458. Database.IsUASupportingBlobStorage = false;
  3459. }
  3460. image.src = url;
  3461. }
  3462. }
  3463. else {
  3464. image.src = url;
  3465. }
  3466. }, false);
  3467. xhr.addEventListener("error", function (event) {
  3468. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3469. image.src = url;
  3470. }, false);
  3471. xhr.send();
  3472. }
  3473. else {
  3474. image.src = url;
  3475. }
  3476. }
  3477. else {
  3478. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3479. image.src = url;
  3480. }
  3481. };
  3482. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3483. var _this = this;
  3484. var updateVersion = function (event) {
  3485. // the version is not yet in the DB or we need to update it
  3486. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3487. };
  3488. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3489. };
  3490. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3491. var _this = this;
  3492. if (this.isSupported) {
  3493. var version;
  3494. try {
  3495. var transaction = this.db.transaction(["versions"]);
  3496. transaction.oncomplete = function (event) {
  3497. if (version) {
  3498. // If the version in the JSON file is > than the version in DB
  3499. if (_this.manifestVersionFound > version.data) {
  3500. _this.mustUpdateRessources = true;
  3501. updateInDBCallback();
  3502. }
  3503. else {
  3504. callback(version.data);
  3505. }
  3506. }
  3507. else {
  3508. _this.mustUpdateRessources = true;
  3509. updateInDBCallback();
  3510. }
  3511. };
  3512. transaction.onabort = function (event) {
  3513. callback(-1);
  3514. };
  3515. var getRequest = transaction.objectStore("versions").get(url);
  3516. getRequest.onsuccess = function (event) {
  3517. version = (event.target).result;
  3518. };
  3519. getRequest.onerror = function (event) {
  3520. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3521. callback(-1);
  3522. };
  3523. }
  3524. catch (ex) {
  3525. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3526. callback(-1);
  3527. }
  3528. }
  3529. else {
  3530. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3531. callback(-1);
  3532. }
  3533. };
  3534. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3535. var _this = this;
  3536. if (this.isSupported && !this.hasReachedQuota) {
  3537. try {
  3538. // Open a transaction to the database
  3539. var transaction = this.db.transaction(["versions"], "readwrite");
  3540. // the transaction could abort because of a QuotaExceededError error
  3541. transaction.onabort = function (event) {
  3542. try {
  3543. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3544. _this.hasReachedQuota = true;
  3545. }
  3546. }
  3547. catch (ex) { }
  3548. callback(-1);
  3549. };
  3550. transaction.oncomplete = function (event) {
  3551. callback(_this.manifestVersionFound);
  3552. };
  3553. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3554. // Put the scene into the database
  3555. var addRequest = transaction.objectStore("versions").put(newVersion);
  3556. addRequest.onsuccess = function (event) {
  3557. };
  3558. addRequest.onerror = function (event) {
  3559. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3560. };
  3561. }
  3562. catch (ex) {
  3563. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3564. callback(-1);
  3565. }
  3566. }
  3567. else {
  3568. callback(-1);
  3569. }
  3570. };
  3571. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3572. var _this = this;
  3573. var completeUrl = Database.ReturnFullUrlLocation(url);
  3574. var saveAndLoadFile = function (event) {
  3575. // the scene is not yet in the DB, let's try to save it
  3576. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3577. };
  3578. this._checkVersionFromDB(completeUrl, function (version) {
  3579. if (version !== -1) {
  3580. if (!_this.mustUpdateRessources) {
  3581. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3582. }
  3583. else {
  3584. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3585. }
  3586. }
  3587. else {
  3588. errorCallback();
  3589. }
  3590. });
  3591. };
  3592. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3593. if (this.isSupported) {
  3594. var targetStore;
  3595. if (url.indexOf(".babylon") !== -1) {
  3596. targetStore = "scenes";
  3597. }
  3598. else {
  3599. targetStore = "textures";
  3600. }
  3601. var file;
  3602. var transaction = this.db.transaction([targetStore]);
  3603. transaction.oncomplete = function (event) {
  3604. if (file) {
  3605. callback(file.data);
  3606. }
  3607. else {
  3608. notInDBCallback();
  3609. }
  3610. };
  3611. transaction.onabort = function (event) {
  3612. notInDBCallback();
  3613. };
  3614. var getRequest = transaction.objectStore(targetStore).get(url);
  3615. getRequest.onsuccess = function (event) {
  3616. file = (event.target).result;
  3617. };
  3618. getRequest.onerror = function (event) {
  3619. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3620. notInDBCallback();
  3621. };
  3622. }
  3623. else {
  3624. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3625. callback();
  3626. }
  3627. };
  3628. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3629. var _this = this;
  3630. if (this.isSupported) {
  3631. var targetStore;
  3632. if (url.indexOf(".babylon") !== -1) {
  3633. targetStore = "scenes";
  3634. }
  3635. else {
  3636. targetStore = "textures";
  3637. }
  3638. // Create XHR
  3639. var xhr = new XMLHttpRequest(), fileData;
  3640. xhr.open("GET", url, true);
  3641. if (useArrayBuffer) {
  3642. xhr.responseType = "arraybuffer";
  3643. }
  3644. xhr.onprogress = progressCallback;
  3645. xhr.addEventListener("load", function () {
  3646. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3647. // Blob as response (XHR2)
  3648. //fileData = xhr.responseText;
  3649. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3650. if (!_this.hasReachedQuota) {
  3651. // Open a transaction to the database
  3652. var transaction = _this.db.transaction([targetStore], "readwrite");
  3653. // the transaction could abort because of a QuotaExceededError error
  3654. transaction.onabort = function (event) {
  3655. try {
  3656. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3657. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3658. this.hasReachedQuota = true;
  3659. }
  3660. }
  3661. catch (ex) { }
  3662. callback(fileData);
  3663. };
  3664. transaction.oncomplete = function (event) {
  3665. callback(fileData);
  3666. };
  3667. var newFile;
  3668. if (targetStore === "scenes") {
  3669. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3670. }
  3671. else {
  3672. newFile = { textureUrl: url, data: fileData };
  3673. }
  3674. try {
  3675. // Put the scene into the database
  3676. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3677. addRequest.onsuccess = function (event) {
  3678. };
  3679. addRequest.onerror = function (event) {
  3680. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3681. };
  3682. }
  3683. catch (ex) {
  3684. callback(fileData);
  3685. }
  3686. }
  3687. else {
  3688. callback(fileData);
  3689. }
  3690. }
  3691. else {
  3692. callback();
  3693. }
  3694. }, false);
  3695. xhr.addEventListener("error", function (event) {
  3696. BABYLON.Tools.Error("error on XHR request.");
  3697. callback();
  3698. }, false);
  3699. xhr.send();
  3700. }
  3701. else {
  3702. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3703. callback();
  3704. }
  3705. };
  3706. Database.IsUASupportingBlobStorage = true;
  3707. Database.IDBStorageEnabled = true;
  3708. Database.parseURL = function (url) {
  3709. var a = document.createElement('a');
  3710. a.href = url;
  3711. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3712. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3713. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3714. return absLocation;
  3715. };
  3716. Database.ReturnFullUrlLocation = function (url) {
  3717. if (url.indexOf("http:/") === -1) {
  3718. return (Database.parseURL(window.location.href) + url);
  3719. }
  3720. else {
  3721. return url;
  3722. }
  3723. };
  3724. return Database;
  3725. })();
  3726. BABYLON.Database = Database;
  3727. })(BABYLON || (BABYLON = {}));
  3728. var BABYLON;
  3729. (function (BABYLON) {
  3730. var Internals;
  3731. (function (Internals) {
  3732. /*
  3733. * Based on jsTGALoader - Javascript loader for TGA file
  3734. * By Vincent Thibault
  3735. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3736. */
  3737. var TGATools = (function () {
  3738. function TGATools() {
  3739. }
  3740. TGATools.GetTGAHeader = function (data) {
  3741. var offset = 0;
  3742. var header = {
  3743. id_length: data[offset++],
  3744. colormap_type: data[offset++],
  3745. image_type: data[offset++],
  3746. colormap_index: data[offset++] | data[offset++] << 8,
  3747. colormap_length: data[offset++] | data[offset++] << 8,
  3748. colormap_size: data[offset++],
  3749. origin: [
  3750. data[offset++] | data[offset++] << 8,
  3751. data[offset++] | data[offset++] << 8
  3752. ],
  3753. width: data[offset++] | data[offset++] << 8,
  3754. height: data[offset++] | data[offset++] << 8,
  3755. pixel_size: data[offset++],
  3756. flags: data[offset++]
  3757. };
  3758. return header;
  3759. };
  3760. TGATools.UploadContent = function (gl, data) {
  3761. // Not enough data to contain header ?
  3762. if (data.length < 19) {
  3763. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3764. return;
  3765. }
  3766. // Read Header
  3767. var offset = 18;
  3768. var header = TGATools.GetTGAHeader(data);
  3769. // Assume it's a valid Targa file.
  3770. if (header.id_length + offset > data.length) {
  3771. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3772. return;
  3773. }
  3774. // Skip not needed data
  3775. offset += header.id_length;
  3776. var use_rle = false;
  3777. var use_pal = false;
  3778. var use_rgb = false;
  3779. var use_grey = false;
  3780. // Get some informations.
  3781. switch (header.image_type) {
  3782. case TGATools._TYPE_RLE_INDEXED:
  3783. use_rle = true;
  3784. case TGATools._TYPE_INDEXED:
  3785. use_pal = true;
  3786. break;
  3787. case TGATools._TYPE_RLE_RGB:
  3788. use_rle = true;
  3789. case TGATools._TYPE_RGB:
  3790. use_rgb = true;
  3791. break;
  3792. case TGATools._TYPE_RLE_GREY:
  3793. use_rle = true;
  3794. case TGATools._TYPE_GREY:
  3795. use_grey = true;
  3796. break;
  3797. }
  3798. var pixel_data;
  3799. var numAlphaBits = header.flags & 0xf;
  3800. var pixel_size = header.pixel_size >> 3;
  3801. var pixel_total = header.width * header.height * pixel_size;
  3802. // Read palettes
  3803. var palettes;
  3804. if (use_pal) {
  3805. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3806. }
  3807. // Read LRE
  3808. if (use_rle) {
  3809. pixel_data = new Uint8Array(pixel_total);
  3810. var c, count, i;
  3811. var localOffset = 0;
  3812. var pixels = new Uint8Array(pixel_size);
  3813. while (offset < pixel_total && localOffset < pixel_total) {
  3814. c = data[offset++];
  3815. count = (c & 0x7f) + 1;
  3816. // RLE pixels
  3817. if (c & 0x80) {
  3818. // Bind pixel tmp array
  3819. for (i = 0; i < pixel_size; ++i) {
  3820. pixels[i] = data[offset++];
  3821. }
  3822. // Copy pixel array
  3823. for (i = 0; i < count; ++i) {
  3824. pixel_data.set(pixels, localOffset + i * pixel_size);
  3825. }
  3826. localOffset += pixel_size * count;
  3827. }
  3828. else {
  3829. count *= pixel_size;
  3830. for (i = 0; i < count; ++i) {
  3831. pixel_data[localOffset + i] = data[offset++];
  3832. }
  3833. localOffset += count;
  3834. }
  3835. }
  3836. }
  3837. else {
  3838. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3839. }
  3840. // Load to texture
  3841. var x_start, y_start, x_step, y_step, y_end, x_end;
  3842. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3843. default:
  3844. case TGATools._ORIGIN_UL:
  3845. x_start = 0;
  3846. x_step = 1;
  3847. x_end = header.width;
  3848. y_start = 0;
  3849. y_step = 1;
  3850. y_end = header.height;
  3851. break;
  3852. case TGATools._ORIGIN_BL:
  3853. x_start = 0;
  3854. x_step = 1;
  3855. x_end = header.width;
  3856. y_start = header.height - 1;
  3857. y_step = -1;
  3858. y_end = -1;
  3859. break;
  3860. case TGATools._ORIGIN_UR:
  3861. x_start = header.width - 1;
  3862. x_step = -1;
  3863. x_end = -1;
  3864. y_start = 0;
  3865. y_step = 1;
  3866. y_end = header.height;
  3867. break;
  3868. case TGATools._ORIGIN_BR:
  3869. x_start = header.width - 1;
  3870. x_step = -1;
  3871. x_end = -1;
  3872. y_start = header.height - 1;
  3873. y_step = -1;
  3874. y_end = -1;
  3875. break;
  3876. }
  3877. // Load the specify method
  3878. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3879. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3880. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3881. };
  3882. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3883. var image = pixel_data, colormap = palettes;
  3884. var width = header.width, height = header.height;
  3885. var color, i = 0, x, y;
  3886. var imageData = new Uint8Array(width * height * 4);
  3887. for (y = y_start; y !== y_end; y += y_step) {
  3888. for (x = x_start; x !== x_end; x += x_step, i++) {
  3889. color = image[i];
  3890. imageData[(x + width * y) * 4 + 3] = 255;
  3891. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3892. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3893. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3894. }
  3895. }
  3896. return imageData;
  3897. };
  3898. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3899. var image = pixel_data;
  3900. var width = header.width, height = header.height;
  3901. var color, i = 0, x, y;
  3902. var imageData = new Uint8Array(width * height * 4);
  3903. for (y = y_start; y !== y_end; y += y_step) {
  3904. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3905. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3906. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3907. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3908. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3909. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3910. }
  3911. }
  3912. return imageData;
  3913. };
  3914. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3915. var image = pixel_data;
  3916. var width = header.width, height = header.height;
  3917. var i = 0, x, y;
  3918. var imageData = new Uint8Array(width * height * 4);
  3919. for (y = y_start; y !== y_end; y += y_step) {
  3920. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3921. imageData[(x + width * y) * 4 + 3] = 255;
  3922. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3923. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3924. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3925. }
  3926. }
  3927. return imageData;
  3928. };
  3929. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3930. var image = pixel_data;
  3931. var width = header.width, height = header.height;
  3932. var i = 0, x, y;
  3933. var imageData = new Uint8Array(width * height * 4);
  3934. for (y = y_start; y !== y_end; y += y_step) {
  3935. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3936. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3937. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3938. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3939. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3940. }
  3941. }
  3942. return imageData;
  3943. };
  3944. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3945. var image = pixel_data;
  3946. var width = header.width, height = header.height;
  3947. var color, i = 0, x, y;
  3948. var imageData = new Uint8Array(width * height * 4);
  3949. for (y = y_start; y !== y_end; y += y_step) {
  3950. for (x = x_start; x !== x_end; x += x_step, i++) {
  3951. color = image[i];
  3952. imageData[(x + width * y) * 4 + 0] = color;
  3953. imageData[(x + width * y) * 4 + 1] = color;
  3954. imageData[(x + width * y) * 4 + 2] = color;
  3955. imageData[(x + width * y) * 4 + 3] = 255;
  3956. }
  3957. }
  3958. return imageData;
  3959. };
  3960. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3961. var image = pixel_data;
  3962. var width = header.width, height = header.height;
  3963. var i = 0, x, y;
  3964. var imageData = new Uint8Array(width * height * 4);
  3965. for (y = y_start; y !== y_end; y += y_step) {
  3966. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3967. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3968. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3969. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3970. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3971. }
  3972. }
  3973. return imageData;
  3974. };
  3975. TGATools._TYPE_NO_DATA = 0;
  3976. TGATools._TYPE_INDEXED = 1;
  3977. TGATools._TYPE_RGB = 2;
  3978. TGATools._TYPE_GREY = 3;
  3979. TGATools._TYPE_RLE_INDEXED = 9;
  3980. TGATools._TYPE_RLE_RGB = 10;
  3981. TGATools._TYPE_RLE_GREY = 11;
  3982. TGATools._ORIGIN_MASK = 0x30;
  3983. TGATools._ORIGIN_SHIFT = 0x04;
  3984. TGATools._ORIGIN_BL = 0x00;
  3985. TGATools._ORIGIN_BR = 0x01;
  3986. TGATools._ORIGIN_UL = 0x02;
  3987. TGATools._ORIGIN_UR = 0x03;
  3988. return TGATools;
  3989. })();
  3990. Internals.TGATools = TGATools;
  3991. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3992. })(BABYLON || (BABYLON = {}));
  3993. var BABYLON;
  3994. (function (BABYLON) {
  3995. var SmartArray = (function () {
  3996. function SmartArray(capacity) {
  3997. this.length = 0;
  3998. this._duplicateId = 0;
  3999. this.data = new Array(capacity);
  4000. this._id = SmartArray._GlobalId++;
  4001. }
  4002. SmartArray.prototype.push = function (value) {
  4003. this.data[this.length++] = value;
  4004. if (this.length > this.data.length) {
  4005. this.data.length *= 2;
  4006. }
  4007. if (!value.__smartArrayFlags) {
  4008. value.__smartArrayFlags = {};
  4009. }
  4010. value.__smartArrayFlags[this._id] = this._duplicateId;
  4011. };
  4012. SmartArray.prototype.pushNoDuplicate = function (value) {
  4013. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4014. return;
  4015. }
  4016. this.push(value);
  4017. };
  4018. SmartArray.prototype.sort = function (compareFn) {
  4019. this.data.sort(compareFn);
  4020. };
  4021. SmartArray.prototype.reset = function () {
  4022. this.length = 0;
  4023. this._duplicateId++;
  4024. };
  4025. SmartArray.prototype.concat = function (array) {
  4026. if (array.length === 0) {
  4027. return;
  4028. }
  4029. if (this.length + array.length > this.data.length) {
  4030. this.data.length = (this.length + array.length) * 2;
  4031. }
  4032. for (var index = 0; index < array.length; index++) {
  4033. this.data[this.length++] = (array.data || array)[index];
  4034. }
  4035. };
  4036. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4037. if (array.length === 0) {
  4038. return;
  4039. }
  4040. if (this.length + array.length > this.data.length) {
  4041. this.data.length = (this.length + array.length) * 2;
  4042. }
  4043. for (var index = 0; index < array.length; index++) {
  4044. var item = (array.data || array)[index];
  4045. this.pushNoDuplicate(item);
  4046. }
  4047. };
  4048. SmartArray.prototype.indexOf = function (value) {
  4049. var position = this.data.indexOf(value);
  4050. if (position >= this.length) {
  4051. return -1;
  4052. }
  4053. return position;
  4054. };
  4055. // Statics
  4056. SmartArray._GlobalId = 0;
  4057. return SmartArray;
  4058. })();
  4059. BABYLON.SmartArray = SmartArray;
  4060. })(BABYLON || (BABYLON = {}));
  4061. var BABYLON;
  4062. (function (BABYLON) {
  4063. var SmartCollection = (function () {
  4064. function SmartCollection(capacity) {
  4065. if (capacity === void 0) { capacity = 10; }
  4066. this.count = 0;
  4067. this._initialCapacity = capacity;
  4068. this.items = {};
  4069. this._keys = new Array(this._initialCapacity);
  4070. }
  4071. SmartCollection.prototype.add = function (key, item) {
  4072. if (this.items[key] != undefined) {
  4073. return -1;
  4074. }
  4075. this.items[key] = item;
  4076. //literal keys are always strings, but we keep source type of key in _keys array
  4077. this._keys[this.count++] = key;
  4078. if (this.count > this._keys.length) {
  4079. this._keys.length *= 2;
  4080. }
  4081. return this.count;
  4082. };
  4083. SmartCollection.prototype.remove = function (key) {
  4084. if (this.items[key] == undefined) {
  4085. return -1;
  4086. }
  4087. return this.removeItemOfIndex(this.indexOf(key));
  4088. };
  4089. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4090. if (index < this.count && index > -1) {
  4091. delete this.items[this._keys[index]];
  4092. //here, shifting by hand is better optimised than .splice
  4093. while (index < this.count) {
  4094. this._keys[index] = this._keys[index + 1];
  4095. index++;
  4096. }
  4097. }
  4098. else {
  4099. return -1;
  4100. }
  4101. return --this.count;
  4102. };
  4103. SmartCollection.prototype.indexOf = function (key) {
  4104. for (var i = 0; i !== this.count; i++) {
  4105. if (this._keys[i] === key) {
  4106. return i;
  4107. }
  4108. }
  4109. return -1;
  4110. };
  4111. SmartCollection.prototype.item = function (key) {
  4112. return this.items[key];
  4113. };
  4114. SmartCollection.prototype.getAllKeys = function () {
  4115. if (this.count > 0) {
  4116. var keys = new Array(this.count);
  4117. for (var i = 0; i < this.count; i++) {
  4118. keys[i] = this._keys[i];
  4119. }
  4120. return keys;
  4121. }
  4122. else {
  4123. return undefined;
  4124. }
  4125. };
  4126. SmartCollection.prototype.getKeyByIndex = function (index) {
  4127. if (index < this.count && index > -1) {
  4128. return this._keys[index];
  4129. }
  4130. else {
  4131. return undefined;
  4132. }
  4133. };
  4134. SmartCollection.prototype.getItemByIndex = function (index) {
  4135. if (index < this.count && index > -1) {
  4136. return this.items[this._keys[index]];
  4137. }
  4138. else {
  4139. return undefined;
  4140. }
  4141. };
  4142. SmartCollection.prototype.empty = function () {
  4143. if (this.count > 0) {
  4144. this.count = 0;
  4145. this.items = {};
  4146. this._keys = new Array(this._initialCapacity);
  4147. }
  4148. };
  4149. SmartCollection.prototype.forEach = function (block) {
  4150. var key;
  4151. for (key in this.items) {
  4152. if (this.items.hasOwnProperty(key)) {
  4153. block(this.items[key]);
  4154. }
  4155. }
  4156. };
  4157. return SmartCollection;
  4158. })();
  4159. BABYLON.SmartCollection = SmartCollection;
  4160. })(BABYLON || (BABYLON = {}));
  4161. var BABYLON;
  4162. (function (BABYLON) {
  4163. // Screenshots
  4164. var screenshotCanvas;
  4165. var cloneValue = function (source, destinationObject) {
  4166. if (!source)
  4167. return null;
  4168. if (source instanceof BABYLON.Mesh) {
  4169. return null;
  4170. }
  4171. if (source instanceof BABYLON.SubMesh) {
  4172. return source.clone(destinationObject);
  4173. }
  4174. else if (source.clone) {
  4175. return source.clone();
  4176. }
  4177. return null;
  4178. };
  4179. var Tools = (function () {
  4180. function Tools() {
  4181. }
  4182. Tools.Instantiate = function (className) {
  4183. var arr = className.split(".");
  4184. var fn = (window || this);
  4185. for (var i = 0, len = arr.length; i < len; i++) {
  4186. fn = fn[arr[i]];
  4187. }
  4188. if (typeof fn !== "function") {
  4189. return null;
  4190. }
  4191. return fn;
  4192. };
  4193. Tools.SetImmediate = function (action) {
  4194. if (window.setImmediate) {
  4195. window.setImmediate(action);
  4196. }
  4197. else {
  4198. setTimeout(action, 1);
  4199. }
  4200. };
  4201. Tools.IsExponentOfTwo = function (value) {
  4202. var count = 1;
  4203. do {
  4204. count *= 2;
  4205. } while (count < value);
  4206. return count === value;
  4207. };
  4208. Tools.GetExponentOfTwo = function (value, max) {
  4209. var count = 1;
  4210. do {
  4211. count *= 2;
  4212. } while (count < value);
  4213. if (count > max)
  4214. count = max;
  4215. return count;
  4216. };
  4217. Tools.GetFilename = function (path) {
  4218. var index = path.lastIndexOf("/");
  4219. if (index < 0)
  4220. return path;
  4221. return path.substring(index + 1);
  4222. };
  4223. Tools.GetDOMTextContent = function (element) {
  4224. var result = "";
  4225. var child = element.firstChild;
  4226. while (child) {
  4227. if (child.nodeType === 3) {
  4228. result += child.textContent;
  4229. }
  4230. child = child.nextSibling;
  4231. }
  4232. return result;
  4233. };
  4234. Tools.ToDegrees = function (angle) {
  4235. return angle * 180 / Math.PI;
  4236. };
  4237. Tools.ToRadians = function (angle) {
  4238. return angle * Math.PI / 180;
  4239. };
  4240. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4241. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4242. var output = "";
  4243. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4244. var i = 0;
  4245. var bytes = new Uint8Array(buffer);
  4246. while (i < bytes.length) {
  4247. chr1 = bytes[i++];
  4248. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4249. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4250. enc1 = chr1 >> 2;
  4251. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4252. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4253. enc4 = chr3 & 63;
  4254. if (isNaN(chr2)) {
  4255. enc3 = enc4 = 64;
  4256. }
  4257. else if (isNaN(chr3)) {
  4258. enc4 = 64;
  4259. }
  4260. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4261. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4262. }
  4263. return "data:image/png;base64," + output;
  4264. };
  4265. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4266. if (bias === void 0) { bias = null; }
  4267. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4268. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4269. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4270. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4271. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4272. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4273. }
  4274. if (bias) {
  4275. minimum.x -= minimum.x * bias.x + bias.y;
  4276. minimum.y -= minimum.y * bias.x + bias.y;
  4277. minimum.z -= minimum.z * bias.x + bias.y;
  4278. maximum.x += maximum.x * bias.x + bias.y;
  4279. maximum.y += maximum.y * bias.x + bias.y;
  4280. maximum.z += maximum.z * bias.x + bias.y;
  4281. }
  4282. return {
  4283. minimum: minimum,
  4284. maximum: maximum
  4285. };
  4286. };
  4287. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4288. if (bias === void 0) { bias = null; }
  4289. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4290. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4291. for (var index = start; index < start + count; index++) {
  4292. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4293. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4294. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4295. }
  4296. if (bias) {
  4297. minimum.x -= minimum.x * bias.x + bias.y;
  4298. minimum.y -= minimum.y * bias.x + bias.y;
  4299. minimum.z -= minimum.z * bias.x + bias.y;
  4300. maximum.x += maximum.x * bias.x + bias.y;
  4301. maximum.y += maximum.y * bias.x + bias.y;
  4302. maximum.z += maximum.z * bias.x + bias.y;
  4303. }
  4304. return {
  4305. minimum: minimum,
  4306. maximum: maximum
  4307. };
  4308. };
  4309. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4310. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4311. return undefined;
  4312. return Array.isArray(obj) ? obj : [obj];
  4313. };
  4314. // Misc.
  4315. Tools.GetPointerPrefix = function () {
  4316. var eventPrefix = "pointer";
  4317. // Check if pointer events are supported
  4318. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4319. eventPrefix = "mouse";
  4320. }
  4321. return eventPrefix;
  4322. };
  4323. Tools.QueueNewFrame = function (func) {
  4324. if (window.requestAnimationFrame)
  4325. window.requestAnimationFrame(func);
  4326. else if (window.msRequestAnimationFrame)
  4327. window.msRequestAnimationFrame(func);
  4328. else if (window.webkitRequestAnimationFrame)
  4329. window.webkitRequestAnimationFrame(func);
  4330. else if (window.mozRequestAnimationFrame)
  4331. window.mozRequestAnimationFrame(func);
  4332. else if (window.oRequestAnimationFrame)
  4333. window.oRequestAnimationFrame(func);
  4334. else {
  4335. window.setTimeout(func, 16);
  4336. }
  4337. };
  4338. Tools.RequestFullscreen = function (element) {
  4339. if (element.requestFullscreen)
  4340. element.requestFullscreen();
  4341. else if (element.msRequestFullscreen)
  4342. element.msRequestFullscreen();
  4343. else if (element.webkitRequestFullscreen)
  4344. element.webkitRequestFullscreen();
  4345. else if (element.mozRequestFullScreen)
  4346. element.mozRequestFullScreen();
  4347. };
  4348. Tools.ExitFullscreen = function () {
  4349. if (document.exitFullscreen) {
  4350. document.exitFullscreen();
  4351. }
  4352. else if (document.mozCancelFullScreen) {
  4353. document.mozCancelFullScreen();
  4354. }
  4355. else if (document.webkitCancelFullScreen) {
  4356. document.webkitCancelFullScreen();
  4357. }
  4358. else if (document.msCancelFullScreen) {
  4359. document.msCancelFullScreen();
  4360. }
  4361. };
  4362. // External files
  4363. Tools.CleanUrl = function (url) {
  4364. url = url.replace(/#/mg, "%23");
  4365. return url;
  4366. };
  4367. Tools.LoadImage = function (url, onload, onerror, database) {
  4368. if (url instanceof ArrayBuffer) {
  4369. url = Tools.EncodeArrayBufferTobase64(url);
  4370. }
  4371. url = Tools.CleanUrl(url);
  4372. var img = new Image();
  4373. if (url.substr(0, 5) !== "data:") {
  4374. if (Tools.CorsBehavior) {
  4375. switch (typeof (Tools.CorsBehavior)) {
  4376. case "function":
  4377. var result = Tools.CorsBehavior(url);
  4378. if (result) {
  4379. img.crossOrigin = result;
  4380. }
  4381. break;
  4382. case "string":
  4383. default:
  4384. img.crossOrigin = Tools.CorsBehavior;
  4385. break;
  4386. }
  4387. }
  4388. }
  4389. img.onload = function () {
  4390. onload(img);
  4391. };
  4392. img.onerror = function (err) {
  4393. Tools.Error("Error while trying to load texture: " + url);
  4394. if (Tools.UseFallbackTexture) {
  4395. 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";
  4396. onload(img);
  4397. }
  4398. else {
  4399. onerror();
  4400. }
  4401. };
  4402. var noIndexedDB = function () {
  4403. img.src = url;
  4404. };
  4405. var loadFromIndexedDB = function () {
  4406. database.loadImageFromDB(url, img);
  4407. };
  4408. //ANY database to do!
  4409. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4410. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4411. }
  4412. else {
  4413. if (url.indexOf("file:") === -1) {
  4414. noIndexedDB();
  4415. }
  4416. else {
  4417. try {
  4418. var textureName = url.substring(5);
  4419. var blobURL;
  4420. try {
  4421. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4422. }
  4423. catch (ex) {
  4424. // Chrome doesn't support oneTimeOnly parameter
  4425. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4426. }
  4427. img.src = blobURL;
  4428. }
  4429. catch (e) {
  4430. img.src = null;
  4431. }
  4432. }
  4433. }
  4434. return img;
  4435. };
  4436. //ANY
  4437. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4438. url = Tools.CleanUrl(url);
  4439. var noIndexedDB = function () {
  4440. var request = new XMLHttpRequest();
  4441. var loadUrl = Tools.BaseUrl + url;
  4442. request.open('GET', loadUrl, true);
  4443. if (useArrayBuffer) {
  4444. request.responseType = "arraybuffer";
  4445. }
  4446. request.onprogress = progressCallBack;
  4447. request.onreadystatechange = function () {
  4448. if (request.readyState === 4) {
  4449. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4450. callback(!useArrayBuffer ? request.responseText : request.response);
  4451. }
  4452. else {
  4453. if (onError) {
  4454. onError();
  4455. }
  4456. else {
  4457. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4458. }
  4459. }
  4460. }
  4461. };
  4462. request.send(null);
  4463. };
  4464. var loadFromIndexedDB = function () {
  4465. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4466. };
  4467. if (url.indexOf("file:") !== -1) {
  4468. var fileName = url.substring(5).toLowerCase();
  4469. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4470. }
  4471. else {
  4472. // Caching all files
  4473. if (database && database.enableSceneOffline) {
  4474. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4475. }
  4476. else {
  4477. noIndexedDB();
  4478. }
  4479. }
  4480. };
  4481. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4482. var reader = new FileReader();
  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. reader.readAsDataURL(fileToLoad);
  4489. };
  4490. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4491. var reader = new FileReader();
  4492. reader.onerror = function (e) {
  4493. Tools.Log("Error while reading file: " + fileToLoad.name);
  4494. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4495. };
  4496. reader.onload = function (e) {
  4497. //target doesn't have result from ts 1.3
  4498. callback(e.target['result']);
  4499. };
  4500. reader.onprogress = progressCallBack;
  4501. if (!useArrayBuffer) {
  4502. // Asynchronous read
  4503. reader.readAsText(fileToLoad);
  4504. }
  4505. else {
  4506. reader.readAsArrayBuffer(fileToLoad);
  4507. }
  4508. };
  4509. //returns a downloadable url to a file content.
  4510. Tools.FileAsURL = function (content) {
  4511. var fileBlob = new Blob([content]);
  4512. var url = window.URL || window.webkitURL;
  4513. var link = url.createObjectURL(fileBlob);
  4514. return link;
  4515. };
  4516. // Misc.
  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.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4536. for (var prop in source) {
  4537. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4538. continue;
  4539. }
  4540. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4541. continue;
  4542. }
  4543. var sourceValue = source[prop];
  4544. var typeOfSourceValue = typeof sourceValue;
  4545. if (typeOfSourceValue === "function") {
  4546. continue;
  4547. }
  4548. if (typeOfSourceValue === "object") {
  4549. if (sourceValue instanceof Array) {
  4550. destination[prop] = [];
  4551. if (sourceValue.length > 0) {
  4552. if (typeof sourceValue[0] == "object") {
  4553. for (var index = 0; index < sourceValue.length; index++) {
  4554. var clonedValue = cloneValue(sourceValue[index], destination);
  4555. if (destination[prop].indexOf(clonedValue) === -1) {
  4556. destination[prop].push(clonedValue);
  4557. }
  4558. }
  4559. }
  4560. else {
  4561. destination[prop] = sourceValue.slice(0);
  4562. }
  4563. }
  4564. }
  4565. else {
  4566. destination[prop] = cloneValue(sourceValue, destination);
  4567. }
  4568. }
  4569. else {
  4570. destination[prop] = sourceValue;
  4571. }
  4572. }
  4573. };
  4574. Tools.IsEmpty = function (obj) {
  4575. for (var i in obj) {
  4576. return false;
  4577. }
  4578. return true;
  4579. };
  4580. Tools.RegisterTopRootEvents = function (events) {
  4581. for (var index = 0; index < events.length; index++) {
  4582. var event = events[index];
  4583. window.addEventListener(event.name, event.handler, false);
  4584. try {
  4585. if (window.parent) {
  4586. window.parent.addEventListener(event.name, event.handler, false);
  4587. }
  4588. }
  4589. catch (e) {
  4590. }
  4591. }
  4592. };
  4593. Tools.UnregisterTopRootEvents = function (events) {
  4594. for (var index = 0; index < events.length; index++) {
  4595. var event = events[index];
  4596. window.removeEventListener(event.name, event.handler);
  4597. try {
  4598. if (window.parent) {
  4599. window.parent.removeEventListener(event.name, event.handler);
  4600. }
  4601. }
  4602. catch (e) {
  4603. }
  4604. }
  4605. };
  4606. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4607. // Read the contents of the framebuffer
  4608. var numberOfChannelsByLine = width * 4;
  4609. var halfHeight = height / 2;
  4610. //Reading datas from WebGL
  4611. var data = engine.readPixels(0, 0, width, height);
  4612. //To flip image on Y axis.
  4613. for (var i = 0; i < halfHeight; i++) {
  4614. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4615. var currentCell = j + i * numberOfChannelsByLine;
  4616. var targetLine = height - i - 1;
  4617. var targetCell = j + targetLine * numberOfChannelsByLine;
  4618. var temp = data[currentCell];
  4619. data[currentCell] = data[targetCell];
  4620. data[targetCell] = temp;
  4621. }
  4622. }
  4623. // Create a 2D canvas to store the result
  4624. if (!screenshotCanvas) {
  4625. screenshotCanvas = document.createElement('canvas');
  4626. }
  4627. screenshotCanvas.width = width;
  4628. screenshotCanvas.height = height;
  4629. var context = screenshotCanvas.getContext('2d');
  4630. // Copy the pixels to a 2D canvas
  4631. var imageData = context.createImageData(width, height);
  4632. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4633. var castData = imageData.data;
  4634. castData.set(data);
  4635. context.putImageData(imageData, 0, 0);
  4636. var base64Image = screenshotCanvas.toDataURL();
  4637. if (successCallback) {
  4638. successCallback(base64Image);
  4639. }
  4640. else {
  4641. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4642. if (("download" in document.createElement("a"))) {
  4643. var a = window.document.createElement("a");
  4644. a.href = base64Image;
  4645. var date = new Date();
  4646. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4647. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4648. window.document.body.appendChild(a);
  4649. a.addEventListener("click", function () {
  4650. a.parentElement.removeChild(a);
  4651. });
  4652. a.click();
  4653. }
  4654. else {
  4655. var newWindow = window.open("");
  4656. var img = newWindow.document.createElement("img");
  4657. img.src = base64Image;
  4658. newWindow.document.body.appendChild(img);
  4659. }
  4660. }
  4661. };
  4662. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4663. var width;
  4664. var height;
  4665. //If a precision value is specified
  4666. if (size.precision) {
  4667. width = Math.round(engine.getRenderWidth() * size.precision);
  4668. height = Math.round(width / engine.getAspectRatio(camera));
  4669. size = { width: width, height: height };
  4670. }
  4671. else if (size.width && size.height) {
  4672. width = size.width;
  4673. height = size.height;
  4674. }
  4675. else if (size.width && !size.height) {
  4676. width = size.width;
  4677. height = Math.round(width / engine.getAspectRatio(camera));
  4678. size = { width: width, height: height };
  4679. }
  4680. else if (size.height && !size.width) {
  4681. height = size.height;
  4682. width = Math.round(height * engine.getAspectRatio(camera));
  4683. size = { width: width, height: height };
  4684. }
  4685. else if (!isNaN(size)) {
  4686. height = size;
  4687. width = size;
  4688. }
  4689. else {
  4690. Tools.Error("Invalid 'size' parameter !");
  4691. return;
  4692. }
  4693. var scene = camera.getScene();
  4694. var previousCamera = null;
  4695. if (scene.activeCamera !== camera) {
  4696. previousCamera = scene.activeCamera;
  4697. scene.activeCamera = camera;
  4698. }
  4699. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4700. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4701. texture.renderList = scene.meshes;
  4702. texture.onAfterRender = function () {
  4703. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4704. };
  4705. scene.incrementRenderId();
  4706. texture.render(true);
  4707. texture.dispose();
  4708. if (previousCamera) {
  4709. scene.activeCamera = previousCamera;
  4710. }
  4711. camera.getProjectionMatrix(true); // Force cache refresh;
  4712. };
  4713. // XHR response validator for local file scenario
  4714. Tools.ValidateXHRData = function (xhr, dataType) {
  4715. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4716. if (dataType === void 0) { dataType = 7; }
  4717. try {
  4718. if (dataType & 1) {
  4719. if (xhr.responseText && xhr.responseText.length > 0) {
  4720. return true;
  4721. }
  4722. else if (dataType === 1) {
  4723. return false;
  4724. }
  4725. }
  4726. if (dataType & 2) {
  4727. // Check header width and height since there is no "TGA" magic number
  4728. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4729. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4730. return true;
  4731. }
  4732. else if (dataType === 2) {
  4733. return false;
  4734. }
  4735. }
  4736. if (dataType & 4) {
  4737. // Check for the "DDS" magic number
  4738. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4739. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4740. return true;
  4741. }
  4742. else {
  4743. return false;
  4744. }
  4745. }
  4746. }
  4747. catch (e) {
  4748. }
  4749. return false;
  4750. };
  4751. Object.defineProperty(Tools, "NoneLogLevel", {
  4752. get: function () {
  4753. return Tools._NoneLogLevel;
  4754. },
  4755. enumerable: true,
  4756. configurable: true
  4757. });
  4758. Object.defineProperty(Tools, "MessageLogLevel", {
  4759. get: function () {
  4760. return Tools._MessageLogLevel;
  4761. },
  4762. enumerable: true,
  4763. configurable: true
  4764. });
  4765. Object.defineProperty(Tools, "WarningLogLevel", {
  4766. get: function () {
  4767. return Tools._WarningLogLevel;
  4768. },
  4769. enumerable: true,
  4770. configurable: true
  4771. });
  4772. Object.defineProperty(Tools, "ErrorLogLevel", {
  4773. get: function () {
  4774. return Tools._ErrorLogLevel;
  4775. },
  4776. enumerable: true,
  4777. configurable: true
  4778. });
  4779. Object.defineProperty(Tools, "AllLogLevel", {
  4780. get: function () {
  4781. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4782. },
  4783. enumerable: true,
  4784. configurable: true
  4785. });
  4786. Tools._AddLogEntry = function (entry) {
  4787. Tools._LogCache = entry + Tools._LogCache;
  4788. if (Tools.OnNewCacheEntry) {
  4789. Tools.OnNewCacheEntry(entry);
  4790. }
  4791. };
  4792. Tools._FormatMessage = function (message) {
  4793. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4794. var date = new Date();
  4795. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4796. };
  4797. Tools._LogDisabled = function (message) {
  4798. // nothing to do
  4799. };
  4800. Tools._LogEnabled = function (message) {
  4801. var formattedMessage = Tools._FormatMessage(message);
  4802. console.log("BJS - " + formattedMessage);
  4803. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4804. Tools._AddLogEntry(entry);
  4805. };
  4806. Tools._WarnDisabled = function (message) {
  4807. // nothing to do
  4808. };
  4809. Tools._WarnEnabled = function (message) {
  4810. var formattedMessage = Tools._FormatMessage(message);
  4811. console.warn("BJS - " + formattedMessage);
  4812. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4813. Tools._AddLogEntry(entry);
  4814. };
  4815. Tools._ErrorDisabled = function (message) {
  4816. // nothing to do
  4817. };
  4818. Tools._ErrorEnabled = function (message) {
  4819. Tools.errorsCount++;
  4820. var formattedMessage = Tools._FormatMessage(message);
  4821. console.error("BJS - " + formattedMessage);
  4822. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4823. Tools._AddLogEntry(entry);
  4824. };
  4825. Object.defineProperty(Tools, "LogCache", {
  4826. get: function () {
  4827. return Tools._LogCache;
  4828. },
  4829. enumerable: true,
  4830. configurable: true
  4831. });
  4832. Tools.ClearLogCache = function () {
  4833. Tools._LogCache = "";
  4834. Tools.errorsCount = 0;
  4835. };
  4836. Object.defineProperty(Tools, "LogLevels", {
  4837. set: function (level) {
  4838. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4839. Tools.Log = Tools._LogEnabled;
  4840. }
  4841. else {
  4842. Tools.Log = Tools._LogDisabled;
  4843. }
  4844. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4845. Tools.Warn = Tools._WarnEnabled;
  4846. }
  4847. else {
  4848. Tools.Warn = Tools._WarnDisabled;
  4849. }
  4850. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4851. Tools.Error = Tools._ErrorEnabled;
  4852. }
  4853. else {
  4854. Tools.Error = Tools._ErrorDisabled;
  4855. }
  4856. },
  4857. enumerable: true,
  4858. configurable: true
  4859. });
  4860. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4861. get: function () {
  4862. return Tools._PerformanceNoneLogLevel;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4868. get: function () {
  4869. return Tools._PerformanceUserMarkLogLevel;
  4870. },
  4871. enumerable: true,
  4872. configurable: true
  4873. });
  4874. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4875. get: function () {
  4876. return Tools._PerformanceConsoleLogLevel;
  4877. },
  4878. enumerable: true,
  4879. configurable: true
  4880. });
  4881. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4882. set: function (level) {
  4883. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4884. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4885. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4886. return;
  4887. }
  4888. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4889. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4890. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4891. return;
  4892. }
  4893. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4894. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4895. },
  4896. enumerable: true,
  4897. configurable: true
  4898. });
  4899. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4900. };
  4901. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4902. };
  4903. Tools._StartUserMark = function (counterName, condition) {
  4904. if (condition === void 0) { condition = true; }
  4905. if (!condition || !Tools._performance.mark) {
  4906. return;
  4907. }
  4908. Tools._performance.mark(counterName + "-Begin");
  4909. };
  4910. Tools._EndUserMark = function (counterName, condition) {
  4911. if (condition === void 0) { condition = true; }
  4912. if (!condition || !Tools._performance.mark) {
  4913. return;
  4914. }
  4915. Tools._performance.mark(counterName + "-End");
  4916. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4917. };
  4918. Tools._StartPerformanceConsole = function (counterName, condition) {
  4919. if (condition === void 0) { condition = true; }
  4920. if (!condition) {
  4921. return;
  4922. }
  4923. Tools._StartUserMark(counterName, condition);
  4924. if (console.time) {
  4925. console.time(counterName);
  4926. }
  4927. };
  4928. Tools._EndPerformanceConsole = function (counterName, condition) {
  4929. if (condition === void 0) { condition = true; }
  4930. if (!condition) {
  4931. return;
  4932. }
  4933. Tools._EndUserMark(counterName, condition);
  4934. if (console.time) {
  4935. console.timeEnd(counterName);
  4936. }
  4937. };
  4938. Object.defineProperty(Tools, "Now", {
  4939. get: function () {
  4940. if (window.performance && window.performance.now) {
  4941. return window.performance.now();
  4942. }
  4943. return new Date().getTime();
  4944. },
  4945. enumerable: true,
  4946. configurable: true
  4947. });
  4948. Tools.BaseUrl = "";
  4949. Tools.CorsBehavior = "anonymous";
  4950. Tools.UseFallbackTexture = true;
  4951. // Logs
  4952. Tools._NoneLogLevel = 0;
  4953. Tools._MessageLogLevel = 1;
  4954. Tools._WarningLogLevel = 2;
  4955. Tools._ErrorLogLevel = 4;
  4956. Tools._LogCache = "";
  4957. Tools.errorsCount = 0;
  4958. Tools.Log = Tools._LogEnabled;
  4959. Tools.Warn = Tools._WarnEnabled;
  4960. Tools.Error = Tools._ErrorEnabled;
  4961. // Performances
  4962. Tools._PerformanceNoneLogLevel = 0;
  4963. Tools._PerformanceUserMarkLogLevel = 1;
  4964. Tools._PerformanceConsoleLogLevel = 2;
  4965. Tools._performance = window.performance;
  4966. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4967. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4968. return Tools;
  4969. })();
  4970. BABYLON.Tools = Tools;
  4971. /**
  4972. * An implementation of a loop for asynchronous functions.
  4973. */
  4974. var AsyncLoop = (function () {
  4975. /**
  4976. * Constroctor.
  4977. * @param iterations the number of iterations.
  4978. * @param _fn the function to run each iteration
  4979. * @param _successCallback the callback that will be called upon succesful execution
  4980. * @param offset starting offset.
  4981. */
  4982. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4983. if (offset === void 0) { offset = 0; }
  4984. this.iterations = iterations;
  4985. this._fn = _fn;
  4986. this._successCallback = _successCallback;
  4987. this.index = offset - 1;
  4988. this._done = false;
  4989. }
  4990. /**
  4991. * Execute the next iteration. Must be called after the last iteration was finished.
  4992. */
  4993. AsyncLoop.prototype.executeNext = function () {
  4994. if (!this._done) {
  4995. if (this.index + 1 < this.iterations) {
  4996. ++this.index;
  4997. this._fn(this);
  4998. }
  4999. else {
  5000. this.breakLoop();
  5001. }
  5002. }
  5003. };
  5004. /**
  5005. * Break the loop and run the success callback.
  5006. */
  5007. AsyncLoop.prototype.breakLoop = function () {
  5008. this._done = true;
  5009. this._successCallback();
  5010. };
  5011. /**
  5012. * Helper function
  5013. */
  5014. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5015. if (offset === void 0) { offset = 0; }
  5016. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5017. loop.executeNext();
  5018. return loop;
  5019. };
  5020. /**
  5021. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5022. * @param iterations total number of iterations
  5023. * @param syncedIterations number of synchronous iterations in each async iteration.
  5024. * @param fn the function to call each iteration.
  5025. * @param callback a success call back that will be called when iterating stops.
  5026. * @param breakFunction a break condition (optional)
  5027. * @param timeout timeout settings for the setTimeout function. default - 0.
  5028. * @constructor
  5029. */
  5030. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5031. if (timeout === void 0) { timeout = 0; }
  5032. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5033. if (breakFunction && breakFunction())
  5034. loop.breakLoop();
  5035. else {
  5036. setTimeout(function () {
  5037. for (var i = 0; i < syncedIterations; ++i) {
  5038. var iteration = (loop.index * syncedIterations) + i;
  5039. if (iteration >= iterations)
  5040. break;
  5041. fn(iteration);
  5042. if (breakFunction && breakFunction()) {
  5043. loop.breakLoop();
  5044. break;
  5045. }
  5046. }
  5047. loop.executeNext();
  5048. }, timeout);
  5049. }
  5050. }, callback);
  5051. };
  5052. return AsyncLoop;
  5053. })();
  5054. BABYLON.AsyncLoop = AsyncLoop;
  5055. })(BABYLON || (BABYLON = {}));
  5056. var BABYLON;
  5057. (function (BABYLON) {
  5058. var Internals;
  5059. (function (Internals) {
  5060. var _AlphaState = (function () {
  5061. function _AlphaState() {
  5062. this._isAlphaBlendDirty = false;
  5063. this._isBlendFunctionParametersDirty = false;
  5064. this._alphaBlend = false;
  5065. this._blendFunctionParameters = new Array(4);
  5066. }
  5067. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5068. get: function () {
  5069. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5070. },
  5071. enumerable: true,
  5072. configurable: true
  5073. });
  5074. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5075. get: function () {
  5076. return this._alphaBlend;
  5077. },
  5078. set: function (value) {
  5079. if (this._alphaBlend === value) {
  5080. return;
  5081. }
  5082. this._alphaBlend = value;
  5083. this._isAlphaBlendDirty = true;
  5084. },
  5085. enumerable: true,
  5086. configurable: true
  5087. });
  5088. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5089. if (this._blendFunctionParameters[0] === value0 &&
  5090. this._blendFunctionParameters[1] === value1 &&
  5091. this._blendFunctionParameters[2] === value2 &&
  5092. this._blendFunctionParameters[3] === value3) {
  5093. return;
  5094. }
  5095. this._blendFunctionParameters[0] = value0;
  5096. this._blendFunctionParameters[1] = value1;
  5097. this._blendFunctionParameters[2] = value2;
  5098. this._blendFunctionParameters[3] = value3;
  5099. this._isBlendFunctionParametersDirty = true;
  5100. };
  5101. _AlphaState.prototype.reset = function () {
  5102. this._alphaBlend = false;
  5103. this._blendFunctionParameters[0] = null;
  5104. this._blendFunctionParameters[1] = null;
  5105. this._blendFunctionParameters[2] = null;
  5106. this._blendFunctionParameters[3] = null;
  5107. this._isAlphaBlendDirty = true;
  5108. this._isBlendFunctionParametersDirty = false;
  5109. };
  5110. _AlphaState.prototype.apply = function (gl) {
  5111. if (!this.isDirty) {
  5112. return;
  5113. }
  5114. // Alpha blend
  5115. if (this._isAlphaBlendDirty) {
  5116. if (this._alphaBlend) {
  5117. gl.enable(gl.BLEND);
  5118. }
  5119. else {
  5120. gl.disable(gl.BLEND);
  5121. }
  5122. this._isAlphaBlendDirty = false;
  5123. }
  5124. // Alpha function
  5125. if (this._isBlendFunctionParametersDirty) {
  5126. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5127. this._isBlendFunctionParametersDirty = false;
  5128. }
  5129. };
  5130. return _AlphaState;
  5131. })();
  5132. Internals._AlphaState = _AlphaState;
  5133. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5134. })(BABYLON || (BABYLON = {}));
  5135. var BABYLON;
  5136. (function (BABYLON) {
  5137. var Internals;
  5138. (function (Internals) {
  5139. var _DepthCullingState = (function () {
  5140. function _DepthCullingState() {
  5141. this._isDepthTestDirty = false;
  5142. this._isDepthMaskDirty = false;
  5143. this._isDepthFuncDirty = false;
  5144. this._isCullFaceDirty = false;
  5145. this._isCullDirty = false;
  5146. this._isZOffsetDirty = false;
  5147. }
  5148. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5149. get: function () {
  5150. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5151. },
  5152. enumerable: true,
  5153. configurable: true
  5154. });
  5155. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5156. get: function () {
  5157. return this._zOffset;
  5158. },
  5159. set: function (value) {
  5160. if (this._zOffset === value) {
  5161. return;
  5162. }
  5163. this._zOffset = value;
  5164. this._isZOffsetDirty = true;
  5165. },
  5166. enumerable: true,
  5167. configurable: true
  5168. });
  5169. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5170. get: function () {
  5171. return this._cullFace;
  5172. },
  5173. set: function (value) {
  5174. if (this._cullFace === value) {
  5175. return;
  5176. }
  5177. this._cullFace = value;
  5178. this._isCullFaceDirty = true;
  5179. },
  5180. enumerable: true,
  5181. configurable: true
  5182. });
  5183. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5184. get: function () {
  5185. return this._cull;
  5186. },
  5187. set: function (value) {
  5188. if (this._cull === value) {
  5189. return;
  5190. }
  5191. this._cull = value;
  5192. this._isCullDirty = true;
  5193. },
  5194. enumerable: true,
  5195. configurable: true
  5196. });
  5197. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5198. get: function () {
  5199. return this._depthFunc;
  5200. },
  5201. set: function (value) {
  5202. if (this._depthFunc === value) {
  5203. return;
  5204. }
  5205. this._depthFunc = value;
  5206. this._isDepthFuncDirty = true;
  5207. },
  5208. enumerable: true,
  5209. configurable: true
  5210. });
  5211. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5212. get: function () {
  5213. return this._depthMask;
  5214. },
  5215. set: function (value) {
  5216. if (this._depthMask === value) {
  5217. return;
  5218. }
  5219. this._depthMask = value;
  5220. this._isDepthMaskDirty = true;
  5221. },
  5222. enumerable: true,
  5223. configurable: true
  5224. });
  5225. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5226. get: function () {
  5227. return this._depthTest;
  5228. },
  5229. set: function (value) {
  5230. if (this._depthTest === value) {
  5231. return;
  5232. }
  5233. this._depthTest = value;
  5234. this._isDepthTestDirty = true;
  5235. },
  5236. enumerable: true,
  5237. configurable: true
  5238. });
  5239. _DepthCullingState.prototype.reset = function () {
  5240. this._depthMask = true;
  5241. this._depthTest = true;
  5242. this._depthFunc = null;
  5243. this._cull = null;
  5244. this._cullFace = null;
  5245. this._zOffset = 0;
  5246. this._isDepthTestDirty = true;
  5247. this._isDepthMaskDirty = true;
  5248. this._isDepthFuncDirty = false;
  5249. this._isCullFaceDirty = false;
  5250. this._isCullDirty = false;
  5251. this._isZOffsetDirty = false;
  5252. };
  5253. _DepthCullingState.prototype.apply = function (gl) {
  5254. if (!this.isDirty) {
  5255. return;
  5256. }
  5257. // Cull
  5258. if (this._isCullDirty) {
  5259. if (this.cull) {
  5260. gl.enable(gl.CULL_FACE);
  5261. }
  5262. else {
  5263. gl.disable(gl.CULL_FACE);
  5264. }
  5265. this._isCullDirty = false;
  5266. }
  5267. // Cull face
  5268. if (this._isCullFaceDirty) {
  5269. gl.cullFace(this.cullFace);
  5270. this._isCullFaceDirty = false;
  5271. }
  5272. // Depth mask
  5273. if (this._isDepthMaskDirty) {
  5274. gl.depthMask(this.depthMask);
  5275. this._isDepthMaskDirty = false;
  5276. }
  5277. // Depth test
  5278. if (this._isDepthTestDirty) {
  5279. if (this.depthTest) {
  5280. gl.enable(gl.DEPTH_TEST);
  5281. }
  5282. else {
  5283. gl.disable(gl.DEPTH_TEST);
  5284. }
  5285. this._isDepthTestDirty = false;
  5286. }
  5287. // Depth func
  5288. if (this._isDepthFuncDirty) {
  5289. gl.depthFunc(this.depthFunc);
  5290. this._isDepthFuncDirty = false;
  5291. }
  5292. // zOffset
  5293. if (this._isZOffsetDirty) {
  5294. if (this.zOffset) {
  5295. gl.enable(gl.POLYGON_OFFSET_FILL);
  5296. gl.polygonOffset(this.zOffset, 0);
  5297. }
  5298. else {
  5299. gl.disable(gl.POLYGON_OFFSET_FILL);
  5300. }
  5301. this._isZOffsetDirty = false;
  5302. }
  5303. };
  5304. return _DepthCullingState;
  5305. })();
  5306. Internals._DepthCullingState = _DepthCullingState;
  5307. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5308. })(BABYLON || (BABYLON = {}));
  5309. var BABYLON;
  5310. (function (BABYLON) {
  5311. var compileShader = function (gl, source, type, defines) {
  5312. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5313. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5314. gl.compileShader(shader);
  5315. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5316. throw new Error(gl.getShaderInfoLog(shader));
  5317. }
  5318. return shader;
  5319. };
  5320. var getWebGLTextureType = function (gl, type) {
  5321. var textureType = gl.UNSIGNED_BYTE;
  5322. if (type === Engine.TEXTURETYPE_FLOAT)
  5323. textureType = gl.FLOAT;
  5324. return textureType;
  5325. };
  5326. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5327. var magFilter = gl.NEAREST;
  5328. var minFilter = gl.NEAREST;
  5329. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5330. magFilter = gl.LINEAR;
  5331. if (generateMipMaps) {
  5332. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5333. }
  5334. else {
  5335. minFilter = gl.LINEAR;
  5336. }
  5337. }
  5338. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5339. magFilter = gl.LINEAR;
  5340. if (generateMipMaps) {
  5341. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5342. }
  5343. else {
  5344. minFilter = gl.LINEAR;
  5345. }
  5346. }
  5347. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5348. magFilter = gl.NEAREST;
  5349. if (generateMipMaps) {
  5350. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5351. }
  5352. else {
  5353. minFilter = gl.NEAREST;
  5354. }
  5355. }
  5356. return {
  5357. min: minFilter,
  5358. mag: magFilter
  5359. };
  5360. };
  5361. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5363. var engine = scene.getEngine();
  5364. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5365. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5366. gl.bindTexture(gl.TEXTURE_2D, texture);
  5367. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5368. texture._baseWidth = width;
  5369. texture._baseHeight = height;
  5370. texture._width = potWidth;
  5371. texture._height = potHeight;
  5372. texture.isReady = true;
  5373. processFunction(potWidth, potHeight);
  5374. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5377. if (!noMipmap && !isCompressed) {
  5378. gl.generateMipmap(gl.TEXTURE_2D);
  5379. }
  5380. gl.bindTexture(gl.TEXTURE_2D, null);
  5381. engine.resetTextureCache();
  5382. scene._removePendingData(texture);
  5383. if (onLoad) {
  5384. onLoad();
  5385. }
  5386. };
  5387. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5388. var img;
  5389. var onload = function () {
  5390. loadedImages[index] = img;
  5391. loadedImages._internalCount++;
  5392. scene._removePendingData(img);
  5393. if (loadedImages._internalCount === 6) {
  5394. onfinish(loadedImages);
  5395. }
  5396. };
  5397. var onerror = function () {
  5398. scene._removePendingData(img);
  5399. };
  5400. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5401. scene._addPendingData(img);
  5402. };
  5403. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5404. var loadedImages = [];
  5405. loadedImages._internalCount = 0;
  5406. for (var index = 0; index < 6; index++) {
  5407. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5408. }
  5409. };
  5410. var EngineCapabilities = (function () {
  5411. function EngineCapabilities() {
  5412. }
  5413. return EngineCapabilities;
  5414. })();
  5415. BABYLON.EngineCapabilities = EngineCapabilities;
  5416. /**
  5417. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5418. */
  5419. var Engine = (function () {
  5420. /**
  5421. * @constructor
  5422. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5423. * @param {boolean} [antialias] - enable antialias
  5424. * @param options - further options to be sent to the getContext function
  5425. */
  5426. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5427. var _this = this;
  5428. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5429. // Public members
  5430. this.isFullscreen = false;
  5431. this.isPointerLock = false;
  5432. this.cullBackFaces = true;
  5433. this.renderEvenInBackground = true;
  5434. // To enable/disable IDB support and avoid XHR on .manifest
  5435. this.enableOfflineSupport = true;
  5436. this.scenes = new Array();
  5437. this._windowIsBackground = false;
  5438. this._webGLVersion = "1.0";
  5439. this._drawCalls = 0;
  5440. this._renderingQueueLaunched = false;
  5441. this._activeRenderLoops = [];
  5442. // FPS
  5443. this.fpsRange = 60;
  5444. this.previousFramesDuration = [];
  5445. this.fps = 60;
  5446. this.deltaTime = 0;
  5447. // States
  5448. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5449. this._alphaState = new BABYLON.Internals._AlphaState();
  5450. this._alphaMode = Engine.ALPHA_DISABLE;
  5451. // Cache
  5452. this._loadedTexturesCache = new Array();
  5453. this._maxTextureChannels = 16;
  5454. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5455. this._compiledEffects = {};
  5456. this._uintIndicesCurrentlySet = false;
  5457. this._renderingCanvas = canvas;
  5458. options = options || {};
  5459. options.antialias = antialias;
  5460. if (options.preserveDrawingBuffer === undefined) {
  5461. options.preserveDrawingBuffer = false;
  5462. }
  5463. // GL
  5464. //try {
  5465. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5466. // if (this._gl) {
  5467. // this._webGLVersion = "2.0";
  5468. // }
  5469. //} catch (e) {
  5470. // // Do nothing
  5471. //}
  5472. if (!this._gl) {
  5473. try {
  5474. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5475. }
  5476. catch (e) {
  5477. throw new Error("WebGL not supported");
  5478. }
  5479. }
  5480. if (!this._gl) {
  5481. throw new Error("WebGL not supported");
  5482. }
  5483. this._onBlur = function () {
  5484. _this._windowIsBackground = true;
  5485. };
  5486. this._onFocus = function () {
  5487. _this._windowIsBackground = false;
  5488. };
  5489. window.addEventListener("blur", this._onBlur);
  5490. window.addEventListener("focus", this._onFocus);
  5491. // Viewport
  5492. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5493. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5494. this.resize();
  5495. // Caps
  5496. this._caps = new EngineCapabilities();
  5497. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5498. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5499. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5500. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5501. // Infos
  5502. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5503. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5504. if (rendererInfo != null) {
  5505. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5506. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5507. }
  5508. if (!this._glVendor) {
  5509. this._glVendor = "Unknown vendor";
  5510. }
  5511. if (!this._glRenderer) {
  5512. this._glRenderer = "Unknown renderer";
  5513. }
  5514. // Extensions
  5515. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5516. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5517. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5518. 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');
  5519. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5520. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5521. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5522. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5523. this._caps.highPrecisionShaderSupported = true;
  5524. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5525. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5526. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5527. if (this._gl.getShaderPrecisionFormat) {
  5528. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5529. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5530. }
  5531. // Depth buffer
  5532. this.setDepthBuffer(true);
  5533. this.setDepthFunctionToLessOrEqual();
  5534. this.setDepthWrite(true);
  5535. // Fullscreen
  5536. this._onFullscreenChange = function () {
  5537. if (document.fullscreen !== undefined) {
  5538. _this.isFullscreen = document.fullscreen;
  5539. }
  5540. else if (document.mozFullScreen !== undefined) {
  5541. _this.isFullscreen = document.mozFullScreen;
  5542. }
  5543. else if (document.webkitIsFullScreen !== undefined) {
  5544. _this.isFullscreen = document.webkitIsFullScreen;
  5545. }
  5546. else if (document.msIsFullScreen !== undefined) {
  5547. _this.isFullscreen = document.msIsFullScreen;
  5548. }
  5549. // Pointer lock
  5550. if (_this.isFullscreen && _this._pointerLockRequested) {
  5551. canvas.requestPointerLock = canvas.requestPointerLock ||
  5552. canvas.msRequestPointerLock ||
  5553. canvas.mozRequestPointerLock ||
  5554. canvas.webkitRequestPointerLock;
  5555. if (canvas.requestPointerLock) {
  5556. canvas.requestPointerLock();
  5557. }
  5558. }
  5559. };
  5560. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5561. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5562. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5563. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5564. // Pointer lock
  5565. this._onPointerLockChange = function () {
  5566. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5567. document.webkitPointerLockElement === canvas ||
  5568. document.msPointerLockElement === canvas ||
  5569. document.pointerLockElement === canvas);
  5570. };
  5571. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5572. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5573. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5574. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5575. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5576. Engine.audioEngine = new BABYLON.AudioEngine();
  5577. }
  5578. //default loading screen
  5579. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5580. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5581. }
  5582. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5583. get: function () {
  5584. return Engine._ALPHA_DISABLE;
  5585. },
  5586. enumerable: true,
  5587. configurable: true
  5588. });
  5589. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5590. get: function () {
  5591. return Engine._ALPHA_ONEONE;
  5592. },
  5593. enumerable: true,
  5594. configurable: true
  5595. });
  5596. Object.defineProperty(Engine, "ALPHA_ADD", {
  5597. get: function () {
  5598. return Engine._ALPHA_ADD;
  5599. },
  5600. enumerable: true,
  5601. configurable: true
  5602. });
  5603. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5604. get: function () {
  5605. return Engine._ALPHA_COMBINE;
  5606. },
  5607. enumerable: true,
  5608. configurable: true
  5609. });
  5610. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5611. get: function () {
  5612. return Engine._ALPHA_SUBTRACT;
  5613. },
  5614. enumerable: true,
  5615. configurable: true
  5616. });
  5617. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5618. get: function () {
  5619. return Engine._ALPHA_MULTIPLY;
  5620. },
  5621. enumerable: true,
  5622. configurable: true
  5623. });
  5624. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5625. get: function () {
  5626. return Engine._ALPHA_MAXIMIZED;
  5627. },
  5628. enumerable: true,
  5629. configurable: true
  5630. });
  5631. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5632. get: function () {
  5633. return Engine._DELAYLOADSTATE_NONE;
  5634. },
  5635. enumerable: true,
  5636. configurable: true
  5637. });
  5638. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5639. get: function () {
  5640. return Engine._DELAYLOADSTATE_LOADED;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5646. get: function () {
  5647. return Engine._DELAYLOADSTATE_LOADING;
  5648. },
  5649. enumerable: true,
  5650. configurable: true
  5651. });
  5652. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5653. get: function () {
  5654. return Engine._DELAYLOADSTATE_NOTLOADED;
  5655. },
  5656. enumerable: true,
  5657. configurable: true
  5658. });
  5659. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5660. get: function () {
  5661. return Engine._TEXTUREFORMAT_ALPHA;
  5662. },
  5663. enumerable: true,
  5664. configurable: true
  5665. });
  5666. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5667. get: function () {
  5668. return Engine._TEXTUREFORMAT_LUMINANCE;
  5669. },
  5670. enumerable: true,
  5671. configurable: true
  5672. });
  5673. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5674. get: function () {
  5675. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5676. },
  5677. enumerable: true,
  5678. configurable: true
  5679. });
  5680. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5681. get: function () {
  5682. return Engine._TEXTUREFORMAT_RGB;
  5683. },
  5684. enumerable: true,
  5685. configurable: true
  5686. });
  5687. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5688. get: function () {
  5689. return Engine._TEXTUREFORMAT_RGBA;
  5690. },
  5691. enumerable: true,
  5692. configurable: true
  5693. });
  5694. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5695. get: function () {
  5696. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5697. },
  5698. enumerable: true,
  5699. configurable: true
  5700. });
  5701. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5702. get: function () {
  5703. return Engine._TEXTURETYPE_FLOAT;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(Engine, "Version", {
  5709. get: function () {
  5710. return "2.4.0-alpha";
  5711. },
  5712. enumerable: true,
  5713. configurable: true
  5714. });
  5715. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5716. get: function () {
  5717. return this._webGLVersion;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Engine.prototype._prepareWorkingCanvas = function () {
  5723. if (this._workingCanvas) {
  5724. return;
  5725. }
  5726. this._workingCanvas = document.createElement("canvas");
  5727. this._workingContext = this._workingCanvas.getContext("2d");
  5728. };
  5729. Engine.prototype.resetTextureCache = function () {
  5730. for (var index = 0; index < this._maxTextureChannels; index++) {
  5731. this._activeTexturesCache[index] = null;
  5732. }
  5733. };
  5734. Engine.prototype.getGlInfo = function () {
  5735. return {
  5736. vendor: this._glVendor,
  5737. renderer: this._glRenderer,
  5738. version: this._glVersion
  5739. };
  5740. };
  5741. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5742. if (useScreen === void 0) { useScreen = false; }
  5743. var viewport = camera.viewport;
  5744. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5745. };
  5746. Engine.prototype.getRenderWidth = function (useScreen) {
  5747. if (useScreen === void 0) { useScreen = false; }
  5748. if (!useScreen && this._currentRenderTarget) {
  5749. return this._currentRenderTarget._width;
  5750. }
  5751. return this._renderingCanvas.width;
  5752. };
  5753. Engine.prototype.getRenderHeight = function (useScreen) {
  5754. if (useScreen === void 0) { useScreen = false; }
  5755. if (!useScreen && this._currentRenderTarget) {
  5756. return this._currentRenderTarget._height;
  5757. }
  5758. return this._renderingCanvas.height;
  5759. };
  5760. Engine.prototype.getRenderingCanvas = function () {
  5761. return this._renderingCanvas;
  5762. };
  5763. Engine.prototype.getRenderingCanvasClientRect = function () {
  5764. return this._renderingCanvas.getBoundingClientRect();
  5765. };
  5766. Engine.prototype.setHardwareScalingLevel = function (level) {
  5767. this._hardwareScalingLevel = level;
  5768. this.resize();
  5769. };
  5770. Engine.prototype.getHardwareScalingLevel = function () {
  5771. return this._hardwareScalingLevel;
  5772. };
  5773. Engine.prototype.getLoadedTexturesCache = function () {
  5774. return this._loadedTexturesCache;
  5775. };
  5776. Engine.prototype.getCaps = function () {
  5777. return this._caps;
  5778. };
  5779. Object.defineProperty(Engine.prototype, "drawCalls", {
  5780. get: function () {
  5781. return this._drawCalls;
  5782. },
  5783. enumerable: true,
  5784. configurable: true
  5785. });
  5786. // Methods
  5787. Engine.prototype.resetDrawCalls = function () {
  5788. this._drawCalls = 0;
  5789. };
  5790. Engine.prototype.setDepthFunctionToGreater = function () {
  5791. this._depthCullingState.depthFunc = this._gl.GREATER;
  5792. };
  5793. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5794. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5795. };
  5796. Engine.prototype.setDepthFunctionToLess = function () {
  5797. this._depthCullingState.depthFunc = this._gl.LESS;
  5798. };
  5799. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5800. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5801. };
  5802. /**
  5803. * stop executing a render loop function and remove it from the execution array
  5804. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5805. */
  5806. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5807. if (!renderFunction) {
  5808. this._activeRenderLoops = [];
  5809. return;
  5810. }
  5811. var index = this._activeRenderLoops.indexOf(renderFunction);
  5812. if (index >= 0) {
  5813. this._activeRenderLoops.splice(index, 1);
  5814. }
  5815. };
  5816. Engine.prototype._renderLoop = function () {
  5817. var shouldRender = true;
  5818. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5819. shouldRender = false;
  5820. }
  5821. if (shouldRender) {
  5822. // Start new frame
  5823. this.beginFrame();
  5824. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5825. var renderFunction = this._activeRenderLoops[index];
  5826. renderFunction();
  5827. }
  5828. // Present
  5829. this.endFrame();
  5830. }
  5831. if (this._activeRenderLoops.length > 0) {
  5832. // Register new frame
  5833. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5834. }
  5835. else {
  5836. this._renderingQueueLaunched = false;
  5837. }
  5838. };
  5839. /**
  5840. * Register and execute a render loop. The engine can have more than one render function.
  5841. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5842. * @example
  5843. * engine.runRenderLoop(function () {
  5844. * scene.render()
  5845. * })
  5846. */
  5847. Engine.prototype.runRenderLoop = function (renderFunction) {
  5848. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5849. return;
  5850. }
  5851. this._activeRenderLoops.push(renderFunction);
  5852. if (!this._renderingQueueLaunched) {
  5853. this._renderingQueueLaunched = true;
  5854. this._bindedRenderFunction = this._renderLoop.bind(this);
  5855. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5856. }
  5857. };
  5858. /**
  5859. * Toggle full screen mode.
  5860. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5861. */
  5862. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5863. if (this.isFullscreen) {
  5864. BABYLON.Tools.ExitFullscreen();
  5865. }
  5866. else {
  5867. this._pointerLockRequested = requestPointerLock;
  5868. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5869. }
  5870. };
  5871. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5872. this.applyStates();
  5873. if (backBuffer) {
  5874. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5875. }
  5876. if (depthStencil && this._depthCullingState.depthMask) {
  5877. this._gl.clearDepth(1.0);
  5878. }
  5879. var mode = 0;
  5880. if (backBuffer) {
  5881. mode |= this._gl.COLOR_BUFFER_BIT;
  5882. }
  5883. if (depthStencil && this._depthCullingState.depthMask) {
  5884. mode |= this._gl.DEPTH_BUFFER_BIT;
  5885. }
  5886. this._gl.clear(mode);
  5887. };
  5888. /**
  5889. * Set the WebGL's viewport
  5890. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5891. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5892. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5893. */
  5894. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5895. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5896. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5897. var x = viewport.x || 0;
  5898. var y = viewport.y || 0;
  5899. this._cachedViewport = viewport;
  5900. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5901. };
  5902. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5903. this._cachedViewport = null;
  5904. this._gl.viewport(x, y, width, height);
  5905. };
  5906. Engine.prototype.beginFrame = function () {
  5907. this._measureFps();
  5908. };
  5909. Engine.prototype.endFrame = function () {
  5910. //this.flushFramebuffer();
  5911. };
  5912. /**
  5913. * resize the view according to the canvas' size.
  5914. * @example
  5915. * window.addEventListener("resize", function () {
  5916. * engine.resize();
  5917. * });
  5918. */
  5919. Engine.prototype.resize = function () {
  5920. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5921. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5922. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5923. for (var index = 0; index < this.scenes.length; index++) {
  5924. var scene = this.scenes[index];
  5925. if (scene.debugLayer.isVisible()) {
  5926. scene.debugLayer._syncPositions();
  5927. }
  5928. }
  5929. };
  5930. /**
  5931. * force a specific size of the canvas
  5932. * @param {number} width - the new canvas' width
  5933. * @param {number} height - the new canvas' height
  5934. */
  5935. Engine.prototype.setSize = function (width, height) {
  5936. this._renderingCanvas.width = width;
  5937. this._renderingCanvas.height = height;
  5938. for (var index = 0; index < this.scenes.length; index++) {
  5939. var scene = this.scenes[index];
  5940. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5941. var cam = scene.cameras[camIndex];
  5942. cam._currentRenderId = 0;
  5943. }
  5944. }
  5945. };
  5946. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5947. this._currentRenderTarget = texture;
  5948. var gl = this._gl;
  5949. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5950. if (texture.isCube) {
  5951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5952. }
  5953. else {
  5954. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5955. }
  5956. this._gl.viewport(0, 0, texture._width, texture._height);
  5957. this.wipeCaches();
  5958. };
  5959. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5960. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5961. this._currentRenderTarget = null;
  5962. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5963. var gl = this._gl;
  5964. gl.bindTexture(gl.TEXTURE_2D, texture);
  5965. gl.generateMipmap(gl.TEXTURE_2D);
  5966. gl.bindTexture(gl.TEXTURE_2D, null);
  5967. }
  5968. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5969. };
  5970. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5971. if (texture.generateMipMaps) {
  5972. var gl = this._gl;
  5973. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5974. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5975. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5976. }
  5977. };
  5978. Engine.prototype.flushFramebuffer = function () {
  5979. this._gl.flush();
  5980. };
  5981. Engine.prototype.restoreDefaultFramebuffer = function () {
  5982. this._currentRenderTarget = null;
  5983. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5984. this.setViewport(this._cachedViewport);
  5985. this.wipeCaches();
  5986. };
  5987. // VBOs
  5988. Engine.prototype._resetVertexBufferBinding = function () {
  5989. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5990. this._cachedVertexBuffers = null;
  5991. };
  5992. Engine.prototype.createVertexBuffer = function (vertices) {
  5993. var vbo = this._gl.createBuffer();
  5994. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5995. if (vertices instanceof Float32Array) {
  5996. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5997. }
  5998. else {
  5999. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6000. }
  6001. this._resetVertexBufferBinding();
  6002. vbo.references = 1;
  6003. return vbo;
  6004. };
  6005. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6006. var vbo = this._gl.createBuffer();
  6007. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6008. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6009. this._resetVertexBufferBinding();
  6010. vbo.references = 1;
  6011. return vbo;
  6012. };
  6013. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6014. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6015. if (offset === undefined) {
  6016. offset = 0;
  6017. }
  6018. if (vertices instanceof Float32Array) {
  6019. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6020. }
  6021. else {
  6022. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6023. }
  6024. this._resetVertexBufferBinding();
  6025. };
  6026. Engine.prototype._resetIndexBufferBinding = function () {
  6027. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6028. this._cachedIndexBuffer = null;
  6029. };
  6030. Engine.prototype.createIndexBuffer = function (indices) {
  6031. var vbo = this._gl.createBuffer();
  6032. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6033. // Check for 32 bits indices
  6034. var arrayBuffer;
  6035. var need32Bits = false;
  6036. if (this._caps.uintIndices) {
  6037. for (var index = 0; index < indices.length; index++) {
  6038. if (indices[index] > 65535) {
  6039. need32Bits = true;
  6040. break;
  6041. }
  6042. }
  6043. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6044. }
  6045. else {
  6046. arrayBuffer = new Uint16Array(indices);
  6047. }
  6048. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6049. this._resetIndexBufferBinding();
  6050. vbo.references = 1;
  6051. vbo.is32Bits = need32Bits;
  6052. return vbo;
  6053. };
  6054. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6055. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6056. this._cachedVertexBuffers = vertexBuffer;
  6057. this._cachedEffectForVertexBuffers = effect;
  6058. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6059. var offset = 0;
  6060. for (var index = 0; index < vertexDeclaration.length; index++) {
  6061. var order = effect.getAttributeLocation(index);
  6062. if (order >= 0) {
  6063. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6064. }
  6065. offset += vertexDeclaration[index] * 4;
  6066. }
  6067. }
  6068. if (this._cachedIndexBuffer !== indexBuffer) {
  6069. this._cachedIndexBuffer = indexBuffer;
  6070. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6071. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6072. }
  6073. };
  6074. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6075. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6076. this._cachedVertexBuffers = vertexBuffers;
  6077. this._cachedEffectForVertexBuffers = effect;
  6078. var attributes = effect.getAttributesNames();
  6079. for (var index = 0; index < attributes.length; index++) {
  6080. var order = effect.getAttributeLocation(index);
  6081. if (order >= 0) {
  6082. var vertexBuffer = vertexBuffers[attributes[index]];
  6083. if (!vertexBuffer) {
  6084. continue;
  6085. }
  6086. var stride = vertexBuffer.getStrideSize();
  6087. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6088. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6089. }
  6090. }
  6091. }
  6092. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6093. this._cachedIndexBuffer = indexBuffer;
  6094. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6095. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6096. }
  6097. };
  6098. Engine.prototype._releaseBuffer = function (buffer) {
  6099. buffer.references--;
  6100. if (buffer.references === 0) {
  6101. this._gl.deleteBuffer(buffer);
  6102. return true;
  6103. }
  6104. return false;
  6105. };
  6106. Engine.prototype.createInstancesBuffer = function (capacity) {
  6107. var buffer = this._gl.createBuffer();
  6108. buffer.capacity = capacity;
  6109. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6110. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6111. return buffer;
  6112. };
  6113. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6114. this._gl.deleteBuffer(buffer);
  6115. };
  6116. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6117. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6118. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6119. for (var index = 0; index < 4; index++) {
  6120. var offsetLocation = offsetLocations[index];
  6121. this._gl.enableVertexAttribArray(offsetLocation);
  6122. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6123. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6124. }
  6125. };
  6126. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6127. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6128. for (var index = 0; index < 4; index++) {
  6129. var offsetLocation = offsetLocations[index];
  6130. this._gl.disableVertexAttribArray(offsetLocation);
  6131. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6132. }
  6133. };
  6134. Engine.prototype.applyStates = function () {
  6135. this._depthCullingState.apply(this._gl);
  6136. this._alphaState.apply(this._gl);
  6137. };
  6138. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6139. // Apply states
  6140. this.applyStates();
  6141. this._drawCalls++;
  6142. // Render
  6143. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6144. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6145. if (instancesCount) {
  6146. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6147. return;
  6148. }
  6149. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6150. };
  6151. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6152. // Apply states
  6153. this.applyStates();
  6154. this._drawCalls++;
  6155. if (instancesCount) {
  6156. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6157. return;
  6158. }
  6159. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6160. };
  6161. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6162. // Apply states
  6163. this.applyStates();
  6164. this._drawCalls++;
  6165. if (instancesCount) {
  6166. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6167. return;
  6168. }
  6169. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6170. };
  6171. // Shaders
  6172. Engine.prototype._releaseEffect = function (effect) {
  6173. if (this._compiledEffects[effect._key]) {
  6174. delete this._compiledEffects[effect._key];
  6175. if (effect.getProgram()) {
  6176. this._gl.deleteProgram(effect.getProgram());
  6177. }
  6178. }
  6179. };
  6180. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6181. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6182. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6183. var name = vertex + "+" + fragment + "@" + defines;
  6184. if (this._compiledEffects[name]) {
  6185. return this._compiledEffects[name];
  6186. }
  6187. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6188. effect._key = name;
  6189. this._compiledEffects[name] = effect;
  6190. return effect;
  6191. };
  6192. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6193. if (uniformsNames === void 0) { uniformsNames = []; }
  6194. if (samplers === void 0) { samplers = []; }
  6195. if (defines === void 0) { defines = ""; }
  6196. return this.createEffect({
  6197. vertex: "particles",
  6198. fragmentElement: fragmentName
  6199. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6200. };
  6201. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6202. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6203. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6204. var shaderProgram = this._gl.createProgram();
  6205. this._gl.attachShader(shaderProgram, vertexShader);
  6206. this._gl.attachShader(shaderProgram, fragmentShader);
  6207. this._gl.linkProgram(shaderProgram);
  6208. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6209. if (!linked) {
  6210. var error = this._gl.getProgramInfoLog(shaderProgram);
  6211. if (error) {
  6212. throw new Error(error);
  6213. }
  6214. }
  6215. this._gl.deleteShader(vertexShader);
  6216. this._gl.deleteShader(fragmentShader);
  6217. return shaderProgram;
  6218. };
  6219. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6220. var results = [];
  6221. for (var index = 0; index < uniformsNames.length; index++) {
  6222. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6223. }
  6224. return results;
  6225. };
  6226. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6227. var results = [];
  6228. for (var index = 0; index < attributesNames.length; index++) {
  6229. try {
  6230. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6231. }
  6232. catch (e) {
  6233. results.push(-1);
  6234. }
  6235. }
  6236. return results;
  6237. };
  6238. Engine.prototype.enableEffect = function (effect) {
  6239. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6240. if (effect && effect.onBind) {
  6241. effect.onBind(effect);
  6242. }
  6243. return;
  6244. }
  6245. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6246. // Use program
  6247. this._gl.useProgram(effect.getProgram());
  6248. for (var i in this._vertexAttribArrays) {
  6249. //make sure this is a number)
  6250. var iAsNumber = +i;
  6251. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6252. continue;
  6253. }
  6254. this._vertexAttribArrays[iAsNumber] = false;
  6255. this._gl.disableVertexAttribArray(iAsNumber);
  6256. }
  6257. var attributesCount = effect.getAttributesCount();
  6258. for (var index = 0; index < attributesCount; index++) {
  6259. // Attributes
  6260. var order = effect.getAttributeLocation(index);
  6261. if (order >= 0) {
  6262. this._vertexAttribArrays[order] = true;
  6263. this._gl.enableVertexAttribArray(order);
  6264. }
  6265. }
  6266. this._currentEffect = effect;
  6267. if (effect.onBind) {
  6268. effect.onBind(effect);
  6269. }
  6270. };
  6271. Engine.prototype.setArray = function (uniform, array) {
  6272. if (!uniform)
  6273. return;
  6274. this._gl.uniform1fv(uniform, array);
  6275. };
  6276. Engine.prototype.setArray2 = function (uniform, array) {
  6277. if (!uniform || array.length % 2 !== 0)
  6278. return;
  6279. this._gl.uniform2fv(uniform, array);
  6280. };
  6281. Engine.prototype.setArray3 = function (uniform, array) {
  6282. if (!uniform || array.length % 3 !== 0)
  6283. return;
  6284. this._gl.uniform3fv(uniform, array);
  6285. };
  6286. Engine.prototype.setArray4 = function (uniform, array) {
  6287. if (!uniform || array.length % 4 !== 0)
  6288. return;
  6289. this._gl.uniform4fv(uniform, array);
  6290. };
  6291. Engine.prototype.setMatrices = function (uniform, matrices) {
  6292. if (!uniform)
  6293. return;
  6294. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6295. };
  6296. Engine.prototype.setMatrix = function (uniform, matrix) {
  6297. if (!uniform)
  6298. return;
  6299. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6300. };
  6301. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6302. if (!uniform)
  6303. return;
  6304. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6305. };
  6306. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6307. if (!uniform)
  6308. return;
  6309. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6310. };
  6311. Engine.prototype.setFloat = function (uniform, value) {
  6312. if (!uniform)
  6313. return;
  6314. this._gl.uniform1f(uniform, value);
  6315. };
  6316. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6317. if (!uniform)
  6318. return;
  6319. this._gl.uniform2f(uniform, x, y);
  6320. };
  6321. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6322. if (!uniform)
  6323. return;
  6324. this._gl.uniform3f(uniform, x, y, z);
  6325. };
  6326. Engine.prototype.setBool = function (uniform, bool) {
  6327. if (!uniform)
  6328. return;
  6329. this._gl.uniform1i(uniform, bool);
  6330. };
  6331. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6332. if (!uniform)
  6333. return;
  6334. this._gl.uniform4f(uniform, x, y, z, w);
  6335. };
  6336. Engine.prototype.setColor3 = function (uniform, color3) {
  6337. if (!uniform)
  6338. return;
  6339. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6340. };
  6341. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6342. if (!uniform)
  6343. return;
  6344. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6345. };
  6346. // States
  6347. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6348. if (zOffset === void 0) { zOffset = 0; }
  6349. if (reverseSide === void 0) { reverseSide = false; }
  6350. // Culling
  6351. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6352. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6353. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6354. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6355. if (culling) {
  6356. this._depthCullingState.cullFace = cullFace;
  6357. this._depthCullingState.cull = true;
  6358. }
  6359. else {
  6360. this._depthCullingState.cull = false;
  6361. }
  6362. }
  6363. // Z offset
  6364. this._depthCullingState.zOffset = zOffset;
  6365. };
  6366. Engine.prototype.setDepthBuffer = function (enable) {
  6367. this._depthCullingState.depthTest = enable;
  6368. };
  6369. Engine.prototype.getDepthWrite = function () {
  6370. return this._depthCullingState.depthMask;
  6371. };
  6372. Engine.prototype.setDepthWrite = function (enable) {
  6373. this._depthCullingState.depthMask = enable;
  6374. };
  6375. Engine.prototype.setColorWrite = function (enable) {
  6376. this._gl.colorMask(enable, enable, enable, enable);
  6377. };
  6378. Engine.prototype.setAlphaMode = function (mode) {
  6379. if (this._alphaMode === mode) {
  6380. return;
  6381. }
  6382. switch (mode) {
  6383. case Engine.ALPHA_DISABLE:
  6384. this.setDepthWrite(true);
  6385. this._alphaState.alphaBlend = false;
  6386. break;
  6387. case Engine.ALPHA_COMBINE:
  6388. this.setDepthWrite(false);
  6389. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6390. this._alphaState.alphaBlend = true;
  6391. break;
  6392. case Engine.ALPHA_ONEONE:
  6393. this.setDepthWrite(false);
  6394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6395. this._alphaState.alphaBlend = true;
  6396. break;
  6397. case Engine.ALPHA_ADD:
  6398. this.setDepthWrite(false);
  6399. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6400. this._alphaState.alphaBlend = true;
  6401. break;
  6402. case Engine.ALPHA_SUBTRACT:
  6403. this.setDepthWrite(false);
  6404. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6405. this._alphaState.alphaBlend = true;
  6406. break;
  6407. case Engine.ALPHA_MULTIPLY:
  6408. this.setDepthWrite(false);
  6409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6410. this._alphaState.alphaBlend = true;
  6411. break;
  6412. case Engine.ALPHA_MAXIMIZED:
  6413. this.setDepthWrite(false);
  6414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6415. this._alphaState.alphaBlend = true;
  6416. break;
  6417. }
  6418. this._alphaMode = mode;
  6419. };
  6420. Engine.prototype.getAlphaMode = function () {
  6421. return this._alphaMode;
  6422. };
  6423. Engine.prototype.setAlphaTesting = function (enable) {
  6424. this._alphaTest = enable;
  6425. };
  6426. Engine.prototype.getAlphaTesting = function () {
  6427. return this._alphaTest;
  6428. };
  6429. // Textures
  6430. Engine.prototype.wipeCaches = function () {
  6431. this.resetTextureCache();
  6432. this._currentEffect = null;
  6433. this._depthCullingState.reset();
  6434. this._alphaState.reset();
  6435. this._cachedVertexBuffers = null;
  6436. this._cachedIndexBuffer = null;
  6437. this._cachedEffectForVertexBuffers = null;
  6438. };
  6439. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6440. var gl = this._gl;
  6441. gl.bindTexture(gl.TEXTURE_2D, texture);
  6442. var magFilter = gl.NEAREST;
  6443. var minFilter = gl.NEAREST;
  6444. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6445. magFilter = gl.LINEAR;
  6446. minFilter = gl.LINEAR;
  6447. }
  6448. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6449. magFilter = gl.LINEAR;
  6450. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6451. }
  6452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6454. gl.bindTexture(gl.TEXTURE_2D, null);
  6455. texture.samplingMode = samplingMode;
  6456. };
  6457. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6458. var _this = this;
  6459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6460. if (onLoad === void 0) { onLoad = null; }
  6461. if (onError === void 0) { onError = null; }
  6462. if (buffer === void 0) { buffer = null; }
  6463. var texture = this._gl.createTexture();
  6464. var extension;
  6465. var fromData = false;
  6466. if (url.substr(0, 5) === "data:") {
  6467. fromData = true;
  6468. }
  6469. if (!fromData)
  6470. extension = url.substr(url.length - 4, 4).toLowerCase();
  6471. else {
  6472. var oldUrl = url;
  6473. fromData = oldUrl.split(':');
  6474. url = oldUrl;
  6475. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6476. }
  6477. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6478. var isTGA = (extension === ".tga");
  6479. scene._addPendingData(texture);
  6480. texture.url = url;
  6481. texture.noMipmap = noMipmap;
  6482. texture.references = 1;
  6483. texture.samplingMode = samplingMode;
  6484. this._loadedTexturesCache.push(texture);
  6485. var onerror = function () {
  6486. scene._removePendingData(texture);
  6487. if (onError) {
  6488. onError();
  6489. }
  6490. };
  6491. var callback;
  6492. if (isTGA) {
  6493. callback = function (arrayBuffer) {
  6494. var data = new Uint8Array(arrayBuffer);
  6495. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6496. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6497. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6498. }, onLoad, samplingMode);
  6499. };
  6500. if (!(fromData instanceof Array))
  6501. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6502. callback(arrayBuffer);
  6503. }, onerror, scene.database, true);
  6504. else
  6505. callback(buffer);
  6506. }
  6507. else if (isDDS) {
  6508. callback = function (data) {
  6509. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6510. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6511. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6512. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6513. }, onLoad, samplingMode);
  6514. };
  6515. if (!(fromData instanceof Array))
  6516. BABYLON.Tools.LoadFile(url, function (data) {
  6517. callback(data);
  6518. }, onerror, scene.database, true);
  6519. else
  6520. callback(buffer);
  6521. }
  6522. else {
  6523. var onload = function (img) {
  6524. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6525. var isPot = (img.width === potWidth && img.height === potHeight);
  6526. if (!isPot) {
  6527. _this._prepareWorkingCanvas();
  6528. _this._workingCanvas.width = potWidth;
  6529. _this._workingCanvas.height = potHeight;
  6530. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6531. _this._workingContext.imageSmoothingEnabled = false;
  6532. _this._workingContext.mozImageSmoothingEnabled = false;
  6533. _this._workingContext.oImageSmoothingEnabled = false;
  6534. _this._workingContext.webkitImageSmoothingEnabled = false;
  6535. _this._workingContext.msImageSmoothingEnabled = false;
  6536. }
  6537. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6538. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6539. _this._workingContext.imageSmoothingEnabled = true;
  6540. _this._workingContext.mozImageSmoothingEnabled = true;
  6541. _this._workingContext.oImageSmoothingEnabled = true;
  6542. _this._workingContext.webkitImageSmoothingEnabled = true;
  6543. _this._workingContext.msImageSmoothingEnabled = true;
  6544. }
  6545. }
  6546. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6547. }, onLoad, samplingMode);
  6548. };
  6549. if (!(fromData instanceof Array))
  6550. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6551. else
  6552. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6553. }
  6554. return texture;
  6555. };
  6556. Engine.prototype._getInternalFormat = function (format) {
  6557. var internalFormat = this._gl.RGBA;
  6558. switch (format) {
  6559. case Engine.TEXTUREFORMAT_ALPHA:
  6560. internalFormat = this._gl.ALPHA;
  6561. break;
  6562. case Engine.TEXTUREFORMAT_LUMINANCE:
  6563. internalFormat = this._gl.LUMINANCE;
  6564. break;
  6565. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6566. internalFormat = this._gl.LUMINANCE_ALPHA;
  6567. break;
  6568. case Engine.TEXTUREFORMAT_RGB:
  6569. internalFormat = this._gl.RGB;
  6570. break;
  6571. case Engine.TEXTUREFORMAT_RGBA:
  6572. internalFormat = this._gl.RGBA;
  6573. break;
  6574. }
  6575. return internalFormat;
  6576. };
  6577. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6578. if (compression === void 0) { compression = null; }
  6579. var internalFormat = this._getInternalFormat(format);
  6580. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6581. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6582. if (compression) {
  6583. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6584. }
  6585. else {
  6586. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6587. }
  6588. if (texture.generateMipMaps) {
  6589. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6590. }
  6591. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6592. this.resetTextureCache();
  6593. texture.isReady = true;
  6594. };
  6595. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6596. if (compression === void 0) { compression = null; }
  6597. var texture = this._gl.createTexture();
  6598. texture._baseWidth = width;
  6599. texture._baseHeight = height;
  6600. texture._width = width;
  6601. texture._height = height;
  6602. texture.references = 1;
  6603. this.updateRawTexture(texture, data, format, invertY, compression);
  6604. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6605. // Filters
  6606. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6607. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6609. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6610. texture.samplingMode = samplingMode;
  6611. this._loadedTexturesCache.push(texture);
  6612. return texture;
  6613. };
  6614. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6615. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6616. var texture = this._gl.createTexture();
  6617. texture._baseWidth = width;
  6618. texture._baseHeight = height;
  6619. if (forceExponantOfTwo) {
  6620. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6621. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6622. }
  6623. this.resetTextureCache();
  6624. texture._width = width;
  6625. texture._height = height;
  6626. texture.isReady = false;
  6627. texture.generateMipMaps = generateMipMaps;
  6628. texture.references = 1;
  6629. texture.samplingMode = samplingMode;
  6630. this.updateTextureSamplingMode(samplingMode, texture);
  6631. this._loadedTexturesCache.push(texture);
  6632. return texture;
  6633. };
  6634. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6635. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6636. if (texture.isCube) {
  6637. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6638. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6639. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6640. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6641. }
  6642. else {
  6643. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6645. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6647. }
  6648. };
  6649. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6650. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6651. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6652. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6653. if (texture.generateMipMaps) {
  6654. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6655. }
  6656. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6657. this.resetTextureCache();
  6658. texture.isReady = true;
  6659. };
  6660. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6661. if (texture._isDisabled) {
  6662. return;
  6663. }
  6664. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6665. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6666. try {
  6667. // Testing video texture support
  6668. if (this._videoTextureSupported === undefined) {
  6669. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6670. if (this._gl.getError() !== 0) {
  6671. this._videoTextureSupported = false;
  6672. }
  6673. else {
  6674. this._videoTextureSupported = true;
  6675. }
  6676. }
  6677. // Copy video through the current working canvas if video texture is not supported
  6678. if (!this._videoTextureSupported) {
  6679. if (!texture._workingCanvas) {
  6680. texture._workingCanvas = document.createElement("canvas");
  6681. texture._workingContext = texture._workingCanvas.getContext("2d");
  6682. texture._workingCanvas.width = texture._width;
  6683. texture._workingCanvas.height = texture._height;
  6684. }
  6685. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6686. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6687. }
  6688. else {
  6689. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6690. }
  6691. if (texture.generateMipMaps) {
  6692. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6693. }
  6694. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6695. this.resetTextureCache();
  6696. texture.isReady = true;
  6697. }
  6698. catch (ex) {
  6699. // Something unexpected
  6700. // Let's disable the texture
  6701. texture._isDisabled = true;
  6702. }
  6703. };
  6704. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6705. // old version had a "generateMipMaps" arg instead of options.
  6706. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6707. // in the same way, generateDepthBuffer is defaulted to true
  6708. var generateMipMaps = false;
  6709. var generateDepthBuffer = true;
  6710. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6711. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6712. if (options !== undefined) {
  6713. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6714. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6715. type = options.type === undefined ? type : options.type;
  6716. if (options.samplingMode !== undefined) {
  6717. samplingMode = options.samplingMode;
  6718. }
  6719. if (type === Engine.TEXTURETYPE_FLOAT) {
  6720. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6721. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6722. }
  6723. }
  6724. var gl = this._gl;
  6725. var texture = gl.createTexture();
  6726. gl.bindTexture(gl.TEXTURE_2D, texture);
  6727. var width = size.width || size;
  6728. var height = size.height || size;
  6729. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6730. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6731. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6732. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6733. }
  6734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6736. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6737. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6738. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6739. var depthBuffer;
  6740. // Create the depth buffer
  6741. if (generateDepthBuffer) {
  6742. depthBuffer = gl.createRenderbuffer();
  6743. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6744. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6745. }
  6746. // Create the framebuffer
  6747. var framebuffer = gl.createFramebuffer();
  6748. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6749. if (generateDepthBuffer) {
  6750. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6751. }
  6752. if (generateMipMaps) {
  6753. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6754. }
  6755. // Unbind
  6756. gl.bindTexture(gl.TEXTURE_2D, null);
  6757. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6758. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6759. texture._framebuffer = framebuffer;
  6760. if (generateDepthBuffer) {
  6761. texture._depthBuffer = depthBuffer;
  6762. }
  6763. texture._width = width;
  6764. texture._height = height;
  6765. texture.isReady = true;
  6766. texture.generateMipMaps = generateMipMaps;
  6767. texture.references = 1;
  6768. texture.samplingMode = samplingMode;
  6769. this.resetTextureCache();
  6770. this._loadedTexturesCache.push(texture);
  6771. return texture;
  6772. };
  6773. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6774. var gl = this._gl;
  6775. var texture = gl.createTexture();
  6776. var generateMipMaps = true;
  6777. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6778. if (options !== undefined) {
  6779. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6780. if (options.samplingMode !== undefined) {
  6781. samplingMode = options.samplingMode;
  6782. }
  6783. }
  6784. texture.isCube = true;
  6785. texture.references = 1;
  6786. texture.generateMipMaps = generateMipMaps;
  6787. texture.references = 1;
  6788. texture.samplingMode = samplingMode;
  6789. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6790. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6791. for (var face = 0; face < 6; face++) {
  6792. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6793. }
  6794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6798. // Create the depth buffer
  6799. var depthBuffer = gl.createRenderbuffer();
  6800. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6801. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6802. // Create the framebuffer
  6803. var framebuffer = gl.createFramebuffer();
  6804. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6805. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6806. // Mipmaps
  6807. if (texture.generateMipMaps) {
  6808. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6809. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6810. }
  6811. // Unbind
  6812. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6813. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6814. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6815. texture._framebuffer = framebuffer;
  6816. texture._depthBuffer = depthBuffer;
  6817. this.resetTextureCache();
  6818. texture._width = size;
  6819. texture._height = size;
  6820. texture.isReady = true;
  6821. return texture;
  6822. };
  6823. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6824. var _this = this;
  6825. var gl = this._gl;
  6826. var texture = gl.createTexture();
  6827. texture.isCube = true;
  6828. texture.url = rootUrl;
  6829. texture.references = 1;
  6830. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6831. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6832. if (isDDS) {
  6833. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6834. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6835. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6836. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6837. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6838. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6839. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6840. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6841. }
  6842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6846. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6847. _this.resetTextureCache();
  6848. texture._width = info.width;
  6849. texture._height = info.height;
  6850. texture.isReady = true;
  6851. }, null, null, true);
  6852. }
  6853. else {
  6854. cascadeLoad(rootUrl, scene, function (imgs) {
  6855. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6856. var height = width;
  6857. _this._prepareWorkingCanvas();
  6858. _this._workingCanvas.width = width;
  6859. _this._workingCanvas.height = height;
  6860. var faces = [
  6861. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6862. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6863. ];
  6864. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6865. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6866. for (var index = 0; index < faces.length; index++) {
  6867. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6868. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6869. }
  6870. if (!noMipmap) {
  6871. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6872. }
  6873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6877. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6878. _this.resetTextureCache();
  6879. texture._width = width;
  6880. texture._height = height;
  6881. texture.isReady = true;
  6882. }, files);
  6883. }
  6884. return texture;
  6885. };
  6886. Engine.prototype.updateTextureSize = function (texture, width, height) {
  6887. texture._width = width;
  6888. texture._height = height;
  6889. };
  6890. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6891. var _this = this;
  6892. var gl = this._gl;
  6893. var texture = gl.createTexture();
  6894. scene._addPendingData(texture);
  6895. texture.isCube = true;
  6896. texture.references = 1;
  6897. texture.url = url;
  6898. var internalFormat = this._getInternalFormat(format);
  6899. var textureType = gl.UNSIGNED_BYTE;
  6900. if (type === Engine.TEXTURETYPE_FLOAT) {
  6901. textureType = gl.FLOAT;
  6902. }
  6903. var width = size;
  6904. var height = width;
  6905. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6906. texture._width = width;
  6907. texture._height = height;
  6908. var onerror = function () {
  6909. scene._removePendingData(texture);
  6910. };
  6911. var internalCallback = function (data) {
  6912. var rgbeDataArrays = callback(data);
  6913. var facesIndex = [
  6914. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6915. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6916. ];
  6917. width = texture._width;
  6918. height = texture._height;
  6919. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6920. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6921. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6922. if (!noMipmap && isPot) {
  6923. if (mipmmapGenerator) {
  6924. var arrayTemp = [];
  6925. // Data are known to be in +X +Y +Z -X -Y -Z
  6926. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6927. arrayTemp.push(rgbeDataArrays[0]); // +X
  6928. arrayTemp.push(rgbeDataArrays[3]); // -X
  6929. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6930. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6931. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6932. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6933. var mipData = mipmmapGenerator(arrayTemp);
  6934. for (var level = 0; level < mipData.length; level++) {
  6935. var mipSize = width >> level;
  6936. // mipData is order in +X -X +Y -Y +Z -Z
  6937. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6938. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6939. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6940. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6941. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6942. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6943. }
  6944. }
  6945. else {
  6946. // Data are known to be in +X +Y +Z -X -Y -Z
  6947. for (var index = 0; index < facesIndex.length; index++) {
  6948. var faceData = rgbeDataArrays[index];
  6949. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6950. }
  6951. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6952. }
  6953. }
  6954. else {
  6955. noMipmap = true;
  6956. }
  6957. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6960. }
  6961. else {
  6962. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6964. }
  6965. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6966. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6967. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6968. texture.isReady = true;
  6969. _this.resetTextureCache();
  6970. scene._removePendingData(texture);
  6971. };
  6972. BABYLON.Tools.LoadFile(url, function (data) {
  6973. internalCallback(data);
  6974. }, onerror, scene.database, true);
  6975. return texture;
  6976. };
  6977. ;
  6978. Engine.prototype._releaseTexture = function (texture) {
  6979. var gl = this._gl;
  6980. if (texture._framebuffer) {
  6981. gl.deleteFramebuffer(texture._framebuffer);
  6982. }
  6983. if (texture._depthBuffer) {
  6984. gl.deleteRenderbuffer(texture._depthBuffer);
  6985. }
  6986. gl.deleteTexture(texture);
  6987. // Unbind channels
  6988. this.unbindAllTextures();
  6989. var index = this._loadedTexturesCache.indexOf(texture);
  6990. if (index !== -1) {
  6991. this._loadedTexturesCache.splice(index, 1);
  6992. }
  6993. };
  6994. Engine.prototype.bindSamplers = function (effect) {
  6995. this._gl.useProgram(effect.getProgram());
  6996. var samplers = effect.getSamplers();
  6997. for (var index = 0; index < samplers.length; index++) {
  6998. var uniform = effect.getUniform(samplers[index]);
  6999. this._gl.uniform1i(uniform, index);
  7000. }
  7001. this._currentEffect = null;
  7002. };
  7003. Engine.prototype._bindTexture = function (channel, texture) {
  7004. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7005. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7006. this._activeTexturesCache[channel] = null;
  7007. };
  7008. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7009. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7010. };
  7011. Engine.prototype.unbindAllTextures = function () {
  7012. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7013. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7014. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7015. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7016. this._activeTexturesCache[channel] = null;
  7017. }
  7018. };
  7019. Engine.prototype.setTexture = function (channel, texture) {
  7020. if (channel < 0) {
  7021. return;
  7022. }
  7023. // Not ready?
  7024. if (!texture || !texture.isReady()) {
  7025. if (this._activeTexturesCache[channel] != null) {
  7026. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7027. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7028. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7029. this._activeTexturesCache[channel] = null;
  7030. }
  7031. return;
  7032. }
  7033. // Video
  7034. var alreadyActivated = false;
  7035. if (texture instanceof BABYLON.VideoTexture) {
  7036. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7037. alreadyActivated = true;
  7038. texture.update();
  7039. }
  7040. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7041. texture.delayLoad();
  7042. return;
  7043. }
  7044. if (this._activeTexturesCache[channel] === texture) {
  7045. return;
  7046. }
  7047. this._activeTexturesCache[channel] = texture;
  7048. var internalTexture = texture.getInternalTexture();
  7049. if (!alreadyActivated) {
  7050. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7051. }
  7052. if (internalTexture.isCube) {
  7053. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7054. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7055. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7056. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7057. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7058. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7059. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7060. }
  7061. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7062. }
  7063. else {
  7064. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7065. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7066. internalTexture._cachedWrapU = texture.wrapU;
  7067. switch (texture.wrapU) {
  7068. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7069. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7070. break;
  7071. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7072. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7073. break;
  7074. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7075. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7076. break;
  7077. }
  7078. }
  7079. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7080. internalTexture._cachedWrapV = texture.wrapV;
  7081. switch (texture.wrapV) {
  7082. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7083. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7084. break;
  7085. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7086. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7087. break;
  7088. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7089. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7090. break;
  7091. }
  7092. }
  7093. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7094. }
  7095. };
  7096. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7097. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7098. var value = texture.anisotropicFilteringLevel;
  7099. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7100. value = 1;
  7101. }
  7102. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7103. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7104. texture._cachedAnisotropicFilteringLevel = value;
  7105. }
  7106. };
  7107. Engine.prototype.readPixels = function (x, y, width, height) {
  7108. var data = new Uint8Array(height * width * 4);
  7109. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7110. return data;
  7111. };
  7112. Engine.prototype.releaseInternalTexture = function (texture) {
  7113. if (!texture) {
  7114. return;
  7115. }
  7116. texture.references--;
  7117. // Final reference ?
  7118. if (texture.references === 0) {
  7119. var texturesCache = this.getLoadedTexturesCache();
  7120. var index = texturesCache.indexOf(texture);
  7121. if (index > -1) {
  7122. texturesCache.splice(index, 1);
  7123. }
  7124. this._releaseTexture(texture);
  7125. }
  7126. };
  7127. // Dispose
  7128. Engine.prototype.dispose = function () {
  7129. this.hideLoadingUI();
  7130. this.stopRenderLoop();
  7131. // Release scenes
  7132. while (this.scenes.length) {
  7133. this.scenes[0].dispose();
  7134. }
  7135. // Release audio engine
  7136. Engine.audioEngine.dispose();
  7137. // Release effects
  7138. for (var name in this._compiledEffects) {
  7139. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7140. }
  7141. // Unbind
  7142. for (var i in this._vertexAttribArrays) {
  7143. //making sure this is a string
  7144. var iAsNumber = +i;
  7145. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7146. continue;
  7147. }
  7148. this._gl.disableVertexAttribArray(iAsNumber);
  7149. }
  7150. this._gl = null;
  7151. // Events
  7152. window.removeEventListener("blur", this._onBlur);
  7153. window.removeEventListener("focus", this._onFocus);
  7154. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7155. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7156. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7157. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7158. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7159. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7160. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7161. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7162. };
  7163. // Loading screen
  7164. Engine.prototype.displayLoadingUI = function () {
  7165. this._loadingScreen.displayLoadingUI();
  7166. };
  7167. Engine.prototype.hideLoadingUI = function () {
  7168. this._loadingScreen.hideLoadingUI();
  7169. };
  7170. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7171. get: function () {
  7172. return this._loadingScreen;
  7173. },
  7174. set: function (loadingScreen) {
  7175. this._loadingScreen = loadingScreen;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7181. set: function (text) {
  7182. this._loadingScreen.loadingUIText = text;
  7183. },
  7184. enumerable: true,
  7185. configurable: true
  7186. });
  7187. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7188. set: function (color) {
  7189. this._loadingScreen.loadingUIBackgroundColor = color;
  7190. },
  7191. enumerable: true,
  7192. configurable: true
  7193. });
  7194. // FPS
  7195. Engine.prototype.getFps = function () {
  7196. return this.fps;
  7197. };
  7198. Engine.prototype.getDeltaTime = function () {
  7199. return this.deltaTime;
  7200. };
  7201. Engine.prototype._measureFps = function () {
  7202. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7203. var length = this.previousFramesDuration.length;
  7204. if (length >= 2) {
  7205. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7206. }
  7207. if (length >= this.fpsRange) {
  7208. if (length > this.fpsRange) {
  7209. this.previousFramesDuration.splice(0, 1);
  7210. length = this.previousFramesDuration.length;
  7211. }
  7212. var sum = 0;
  7213. for (var id = 0; id < length - 1; id++) {
  7214. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7215. }
  7216. this.fps = 1000.0 / (sum / (length - 1));
  7217. }
  7218. };
  7219. // Statics
  7220. Engine.isSupported = function () {
  7221. try {
  7222. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7223. if (navigator.isCocoonJS) {
  7224. return true;
  7225. }
  7226. var tempcanvas = document.createElement("canvas");
  7227. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7228. return gl != null && !!window.WebGLRenderingContext;
  7229. }
  7230. catch (e) {
  7231. return false;
  7232. }
  7233. };
  7234. // Const statics
  7235. Engine._ALPHA_DISABLE = 0;
  7236. Engine._ALPHA_ADD = 1;
  7237. Engine._ALPHA_COMBINE = 2;
  7238. Engine._ALPHA_SUBTRACT = 3;
  7239. Engine._ALPHA_MULTIPLY = 4;
  7240. Engine._ALPHA_MAXIMIZED = 5;
  7241. Engine._ALPHA_ONEONE = 6;
  7242. Engine._DELAYLOADSTATE_NONE = 0;
  7243. Engine._DELAYLOADSTATE_LOADED = 1;
  7244. Engine._DELAYLOADSTATE_LOADING = 2;
  7245. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7246. Engine._TEXTUREFORMAT_ALPHA = 0;
  7247. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7248. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7249. Engine._TEXTUREFORMAT_RGB = 4;
  7250. Engine._TEXTUREFORMAT_RGBA = 5;
  7251. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7252. Engine._TEXTURETYPE_FLOAT = 1;
  7253. // Updatable statics so stick with vars here
  7254. Engine.CollisionsEpsilon = 0.001;
  7255. Engine.CodeRepository = "src/";
  7256. Engine.ShadersRepository = "src/Shaders/";
  7257. return Engine;
  7258. })();
  7259. BABYLON.Engine = Engine;
  7260. })(BABYLON || (BABYLON = {}));
  7261. var BABYLON;
  7262. (function (BABYLON) {
  7263. /**
  7264. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7265. */
  7266. var Node = (function () {
  7267. /**
  7268. * @constructor
  7269. * @param {string} name - the name and id to be given to this node
  7270. * @param {BABYLON.Scene} the scene this node will be added to
  7271. */
  7272. function Node(name, scene) {
  7273. this.state = "";
  7274. this.animations = new Array();
  7275. this._ranges = {};
  7276. this._childrenFlag = -1;
  7277. this._isEnabled = true;
  7278. this._isReady = true;
  7279. this._currentRenderId = -1;
  7280. this._parentRenderId = -1;
  7281. this.name = name;
  7282. this.id = name;
  7283. this._scene = scene;
  7284. this._initCache();
  7285. }
  7286. Object.defineProperty(Node.prototype, "parent", {
  7287. get: function () {
  7288. return this._parentNode;
  7289. },
  7290. set: function (parent) {
  7291. if (this._parentNode === parent) {
  7292. return;
  7293. }
  7294. if (this._parentNode) {
  7295. var index = this._parentNode._children.indexOf(this);
  7296. if (index !== -1) {
  7297. this._parentNode._children.splice(index, 1);
  7298. }
  7299. }
  7300. this._parentNode = parent;
  7301. if (this._parentNode) {
  7302. if (!this._parentNode._children) {
  7303. this._parentNode._children = new Array();
  7304. }
  7305. this._parentNode._children.push(this);
  7306. }
  7307. },
  7308. enumerable: true,
  7309. configurable: true
  7310. });
  7311. Node.prototype.getScene = function () {
  7312. return this._scene;
  7313. };
  7314. Node.prototype.getEngine = function () {
  7315. return this._scene.getEngine();
  7316. };
  7317. // override it in derived class
  7318. Node.prototype.getWorldMatrix = function () {
  7319. return BABYLON.Matrix.Identity();
  7320. };
  7321. // override it in derived class if you add new variables to the cache
  7322. // and call the parent class method
  7323. Node.prototype._initCache = function () {
  7324. this._cache = {};
  7325. this._cache.parent = undefined;
  7326. };
  7327. Node.prototype.updateCache = function (force) {
  7328. if (!force && this.isSynchronized())
  7329. return;
  7330. this._cache.parent = this.parent;
  7331. this._updateCache();
  7332. };
  7333. // override it in derived class if you add new variables to the cache
  7334. // and call the parent class method if !ignoreParentClass
  7335. Node.prototype._updateCache = function (ignoreParentClass) {
  7336. };
  7337. // override it in derived class if you add new variables to the cache
  7338. Node.prototype._isSynchronized = function () {
  7339. return true;
  7340. };
  7341. Node.prototype._markSyncedWithParent = function () {
  7342. this._parentRenderId = this.parent._currentRenderId;
  7343. };
  7344. Node.prototype.isSynchronizedWithParent = function () {
  7345. if (!this.parent) {
  7346. return true;
  7347. }
  7348. if (this._parentRenderId !== this.parent._currentRenderId) {
  7349. return false;
  7350. }
  7351. return this.parent.isSynchronized();
  7352. };
  7353. Node.prototype.isSynchronized = function (updateCache) {
  7354. var check = this.hasNewParent();
  7355. check = check || !this.isSynchronizedWithParent();
  7356. check = check || !this._isSynchronized();
  7357. if (updateCache)
  7358. this.updateCache(true);
  7359. return !check;
  7360. };
  7361. Node.prototype.hasNewParent = function (update) {
  7362. if (this._cache.parent === this.parent)
  7363. return false;
  7364. if (update)
  7365. this._cache.parent = this.parent;
  7366. return true;
  7367. };
  7368. /**
  7369. * Is this node ready to be used/rendered
  7370. * @return {boolean} is it ready
  7371. */
  7372. Node.prototype.isReady = function () {
  7373. return this._isReady;
  7374. };
  7375. /**
  7376. * Is this node enabled.
  7377. * If the node has a parent and is enabled, the parent will be inspected as well.
  7378. * @return {boolean} whether this node (and its parent) is enabled.
  7379. * @see setEnabled
  7380. */
  7381. Node.prototype.isEnabled = function () {
  7382. if (!this._isEnabled) {
  7383. return false;
  7384. }
  7385. if (this.parent) {
  7386. return this.parent.isEnabled();
  7387. }
  7388. return true;
  7389. };
  7390. /**
  7391. * Set the enabled state of this node.
  7392. * @param {boolean} value - the new enabled state
  7393. * @see isEnabled
  7394. */
  7395. Node.prototype.setEnabled = function (value) {
  7396. this._isEnabled = value;
  7397. };
  7398. /**
  7399. * Is this node a descendant of the given node.
  7400. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7401. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7402. * @see parent
  7403. */
  7404. Node.prototype.isDescendantOf = function (ancestor) {
  7405. if (this.parent) {
  7406. if (this.parent === ancestor) {
  7407. return true;
  7408. }
  7409. return this.parent.isDescendantOf(ancestor);
  7410. }
  7411. return false;
  7412. };
  7413. /**
  7414. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7415. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7416. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7417. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7418. */
  7419. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7420. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7421. if (!this._children) {
  7422. return;
  7423. }
  7424. for (var index = 0; index < this._children.length; index++) {
  7425. var item = this._children[index];
  7426. if (!predicate || predicate(item)) {
  7427. results.push(item);
  7428. }
  7429. if (!directDescendantsOnly) {
  7430. item._getDescendants(results, false, predicate);
  7431. }
  7432. }
  7433. };
  7434. /**
  7435. * Will return all nodes that have this node as ascendant.
  7436. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  7437. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7438. * @return {BABYLON.Node[]} all children nodes of all types.
  7439. */
  7440. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7441. var results = [];
  7442. this._getDescendants(results, directDescendantsOnly, predicate);
  7443. return results;
  7444. };
  7445. /**
  7446. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  7447. * @Deprecated, legacy support.
  7448. * use getDecendants instead.
  7449. */
  7450. Node.prototype.getChildren = function (predicate) {
  7451. return this.getDescendants(true, predicate);
  7452. };
  7453. /**
  7454. * Get all child-meshes of this node.
  7455. */
  7456. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7457. var results = [];
  7458. this._getDescendants(results, directDecendantsOnly, function (node) {
  7459. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7460. });
  7461. return results;
  7462. };
  7463. Node.prototype._setReady = function (state) {
  7464. if (state === this._isReady) {
  7465. return;
  7466. }
  7467. if (!state) {
  7468. this._isReady = false;
  7469. return;
  7470. }
  7471. this._isReady = true;
  7472. if (this.onReady) {
  7473. this.onReady(this);
  7474. }
  7475. };
  7476. Node.prototype.getAnimationByName = function (name) {
  7477. for (var i = 0; i < this.animations.length; i++) {
  7478. var animation = this.animations[i];
  7479. if (animation.name === name) {
  7480. return animation;
  7481. }
  7482. }
  7483. return null;
  7484. };
  7485. Node.prototype.createAnimationRange = function (name, from, to) {
  7486. // check name not already in use
  7487. if (!this._ranges[name]) {
  7488. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7489. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7490. if (this.animations[i]) {
  7491. this.animations[i].createRange(name, from, to);
  7492. }
  7493. }
  7494. }
  7495. };
  7496. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7497. if (deleteFrames === void 0) { deleteFrames = true; }
  7498. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7499. if (this.animations[i]) {
  7500. this.animations[i].deleteRange(name, deleteFrames);
  7501. }
  7502. }
  7503. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7504. };
  7505. Node.prototype.getAnimationRange = function (name) {
  7506. return this._ranges[name];
  7507. };
  7508. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7509. var range = this.getAnimationRange(name);
  7510. if (!range) {
  7511. return null;
  7512. }
  7513. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7514. };
  7515. Node.prototype.serializeAnimationRanges = function () {
  7516. var serializationRanges = [];
  7517. for (var name in this._ranges) {
  7518. var range = {};
  7519. range.name = name;
  7520. range.from = this._ranges[name].from;
  7521. range.to = this._ranges[name].to;
  7522. serializationRanges.push(range);
  7523. }
  7524. return serializationRanges;
  7525. };
  7526. Node.prototype.dispose = function () {
  7527. this.parent = null;
  7528. };
  7529. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7530. if (parsedNode.ranges) {
  7531. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7532. var data = parsedNode.ranges[index];
  7533. node.createAnimationRange(data.name, data.from, data.to);
  7534. }
  7535. }
  7536. };
  7537. __decorate([
  7538. BABYLON.serialize()
  7539. ], Node.prototype, "name", void 0);
  7540. __decorate([
  7541. BABYLON.serialize()
  7542. ], Node.prototype, "id", void 0);
  7543. __decorate([
  7544. BABYLON.serialize()
  7545. ], Node.prototype, "uniqueId", void 0);
  7546. __decorate([
  7547. BABYLON.serialize()
  7548. ], Node.prototype, "state", void 0);
  7549. return Node;
  7550. })();
  7551. BABYLON.Node = Node;
  7552. })(BABYLON || (BABYLON = {}));
  7553. var BABYLON;
  7554. (function (BABYLON) {
  7555. var FilesInput = (function () {
  7556. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7557. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7558. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7559. this._engine = p_engine;
  7560. this._canvas = p_canvas;
  7561. this._currentScene = p_scene;
  7562. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7563. this._progressCallback = p_progressCallback;
  7564. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7565. this._textureLoadingCallback = p_textureLoadingCallback;
  7566. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7567. }
  7568. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7569. var _this = this;
  7570. if (p_elementToMonitor) {
  7571. this._elementToMonitor = p_elementToMonitor;
  7572. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7573. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7574. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7575. }
  7576. };
  7577. FilesInput.prototype.renderFunction = function () {
  7578. if (this._additionnalRenderLoopLogicCallback) {
  7579. this._additionnalRenderLoopLogicCallback();
  7580. }
  7581. if (this._currentScene) {
  7582. if (this._textureLoadingCallback) {
  7583. var remaining = this._currentScene.getWaitingItemsCount();
  7584. if (remaining > 0) {
  7585. this._textureLoadingCallback(remaining);
  7586. }
  7587. }
  7588. this._currentScene.render();
  7589. }
  7590. };
  7591. FilesInput.prototype.drag = function (e) {
  7592. e.stopPropagation();
  7593. e.preventDefault();
  7594. };
  7595. FilesInput.prototype.drop = function (eventDrop) {
  7596. eventDrop.stopPropagation();
  7597. eventDrop.preventDefault();
  7598. this.loadFiles(eventDrop);
  7599. };
  7600. FilesInput.prototype.loadFiles = function (event) {
  7601. if (this._startingProcessingFilesCallback)
  7602. this._startingProcessingFilesCallback();
  7603. // Handling data transfer via drag'n'drop
  7604. if (event && event.dataTransfer && event.dataTransfer.files) {
  7605. this._filesToLoad = event.dataTransfer.files;
  7606. }
  7607. // Handling files from input files
  7608. if (event && event.target && event.target.files) {
  7609. this._filesToLoad = event.target.files;
  7610. }
  7611. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7612. for (var i = 0; i < this._filesToLoad.length; i++) {
  7613. switch (this._filesToLoad[i].type) {
  7614. case "image/jpeg":
  7615. case "image/png":
  7616. case "image/bmp":
  7617. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7618. break;
  7619. case "image/targa":
  7620. case "image/vnd.ms-dds":
  7621. case "audio/wav":
  7622. case "audio/x-wav":
  7623. case "audio/mp3":
  7624. case "audio/mpeg":
  7625. case "audio/mpeg3":
  7626. case "audio/x-mpeg-3":
  7627. case "audio/ogg":
  7628. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7629. break;
  7630. default:
  7631. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7632. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7633. }
  7634. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7635. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7636. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7637. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7638. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7639. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7640. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7641. this._sceneFileToLoad = this._filesToLoad[i];
  7642. }
  7643. break;
  7644. }
  7645. }
  7646. this.reload();
  7647. }
  7648. };
  7649. FilesInput.prototype.reload = function () {
  7650. var _this = this;
  7651. var that = this;
  7652. // If a ".babylon" file has been provided
  7653. if (this._sceneFileToLoad) {
  7654. if (this._currentScene) {
  7655. if (BABYLON.Tools.errorsCount > 0) {
  7656. BABYLON.Tools.ClearLogCache();
  7657. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7658. }
  7659. this._engine.stopRenderLoop();
  7660. this._currentScene.dispose();
  7661. }
  7662. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7663. that._currentScene = newScene;
  7664. // Wait for textures and shaders to be ready
  7665. that._currentScene.executeWhenReady(function () {
  7666. // Attach camera to canvas inputs
  7667. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7668. that._currentScene.createDefaultCameraOrLight();
  7669. }
  7670. that._currentScene.activeCamera.attachControl(that._canvas);
  7671. if (that._sceneLoadedCallback) {
  7672. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7673. }
  7674. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7675. });
  7676. }, function (progress) {
  7677. if (_this._progressCallback) {
  7678. _this._progressCallback(progress);
  7679. }
  7680. });
  7681. }
  7682. else {
  7683. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7684. }
  7685. };
  7686. FilesInput.FilesTextures = new Array();
  7687. FilesInput.FilesToLoad = new Array();
  7688. return FilesInput;
  7689. })();
  7690. BABYLON.FilesInput = FilesInput;
  7691. })(BABYLON || (BABYLON = {}));
  7692. var BABYLON;
  7693. (function (BABYLON) {
  7694. var IntersectionInfo = (function () {
  7695. function IntersectionInfo(bu, bv, distance) {
  7696. this.bu = bu;
  7697. this.bv = bv;
  7698. this.distance = distance;
  7699. this.faceId = 0;
  7700. this.subMeshId = 0;
  7701. }
  7702. return IntersectionInfo;
  7703. })();
  7704. BABYLON.IntersectionInfo = IntersectionInfo;
  7705. var PickingInfo = (function () {
  7706. function PickingInfo() {
  7707. this.hit = false;
  7708. this.distance = 0;
  7709. this.pickedPoint = null;
  7710. this.pickedMesh = null;
  7711. this.bu = 0;
  7712. this.bv = 0;
  7713. this.faceId = -1;
  7714. this.subMeshId = 0;
  7715. this.pickedSprite = null;
  7716. }
  7717. // Methods
  7718. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7719. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7720. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7721. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7722. return null;
  7723. }
  7724. var indices = this.pickedMesh.getIndices();
  7725. var result;
  7726. if (useVerticesNormals) {
  7727. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7728. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7729. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7730. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7731. normal0 = normal0.scale(this.bu);
  7732. normal1 = normal1.scale(this.bv);
  7733. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7734. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7735. }
  7736. else {
  7737. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7738. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7739. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7740. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7741. var p1p2 = vertex1.subtract(vertex2);
  7742. var p3p2 = vertex3.subtract(vertex2);
  7743. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7744. }
  7745. if (useWorldCoordinates) {
  7746. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7747. }
  7748. return BABYLON.Vector3.Normalize(result);
  7749. };
  7750. PickingInfo.prototype.getTextureCoordinates = function () {
  7751. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7752. return null;
  7753. }
  7754. var indices = this.pickedMesh.getIndices();
  7755. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7756. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7757. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7758. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7759. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7760. uv1 = uv1.scale(this.bu);
  7761. uv2 = uv2.scale(this.bv);
  7762. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7763. };
  7764. return PickingInfo;
  7765. })();
  7766. BABYLON.PickingInfo = PickingInfo;
  7767. })(BABYLON || (BABYLON = {}));
  7768. var BABYLON;
  7769. (function (BABYLON) {
  7770. var BoundingSphere = (function () {
  7771. function BoundingSphere(minimum, maximum) {
  7772. this.minimum = minimum;
  7773. this.maximum = maximum;
  7774. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7775. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7776. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7777. this.radius = distance * 0.5;
  7778. this.centerWorld = BABYLON.Vector3.Zero();
  7779. this._update(BABYLON.Matrix.Identity());
  7780. }
  7781. // Methods
  7782. BoundingSphere.prototype._update = function (world) {
  7783. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7784. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7785. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7786. };
  7787. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7788. for (var i = 0; i < 6; i++) {
  7789. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7790. return false;
  7791. }
  7792. return true;
  7793. };
  7794. BoundingSphere.prototype.intersectsPoint = function (point) {
  7795. var x = this.centerWorld.x - point.x;
  7796. var y = this.centerWorld.y - point.y;
  7797. var z = this.centerWorld.z - point.z;
  7798. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7799. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7800. return false;
  7801. return true;
  7802. };
  7803. // Statics
  7804. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7805. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7806. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7807. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7808. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7809. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7810. return false;
  7811. return true;
  7812. };
  7813. return BoundingSphere;
  7814. })();
  7815. BABYLON.BoundingSphere = BoundingSphere;
  7816. })(BABYLON || (BABYLON = {}));
  7817. var BABYLON;
  7818. (function (BABYLON) {
  7819. var BoundingBox = (function () {
  7820. function BoundingBox(minimum, maximum) {
  7821. this.minimum = minimum;
  7822. this.maximum = maximum;
  7823. this.vectors = new Array();
  7824. this.vectorsWorld = new Array();
  7825. // Bounding vectors
  7826. this.vectors.push(this.minimum.clone());
  7827. this.vectors.push(this.maximum.clone());
  7828. this.vectors.push(this.minimum.clone());
  7829. this.vectors[2].x = this.maximum.x;
  7830. this.vectors.push(this.minimum.clone());
  7831. this.vectors[3].y = this.maximum.y;
  7832. this.vectors.push(this.minimum.clone());
  7833. this.vectors[4].z = this.maximum.z;
  7834. this.vectors.push(this.maximum.clone());
  7835. this.vectors[5].z = this.minimum.z;
  7836. this.vectors.push(this.maximum.clone());
  7837. this.vectors[6].x = this.minimum.x;
  7838. this.vectors.push(this.maximum.clone());
  7839. this.vectors[7].y = this.minimum.y;
  7840. // OBB
  7841. this.center = this.maximum.add(this.minimum).scale(0.5);
  7842. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7843. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7844. // World
  7845. for (var index = 0; index < this.vectors.length; index++) {
  7846. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7847. }
  7848. this.minimumWorld = BABYLON.Vector3.Zero();
  7849. this.maximumWorld = BABYLON.Vector3.Zero();
  7850. this._update(BABYLON.Matrix.Identity());
  7851. }
  7852. // Methods
  7853. BoundingBox.prototype.getWorldMatrix = function () {
  7854. return this._worldMatrix;
  7855. };
  7856. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7857. this._worldMatrix.copyFrom(matrix);
  7858. return this;
  7859. };
  7860. BoundingBox.prototype._update = function (world) {
  7861. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7862. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7863. for (var index = 0; index < this.vectors.length; index++) {
  7864. var v = this.vectorsWorld[index];
  7865. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7866. if (v.x < this.minimumWorld.x)
  7867. this.minimumWorld.x = v.x;
  7868. if (v.y < this.minimumWorld.y)
  7869. this.minimumWorld.y = v.y;
  7870. if (v.z < this.minimumWorld.z)
  7871. this.minimumWorld.z = v.z;
  7872. if (v.x > this.maximumWorld.x)
  7873. this.maximumWorld.x = v.x;
  7874. if (v.y > this.maximumWorld.y)
  7875. this.maximumWorld.y = v.y;
  7876. if (v.z > this.maximumWorld.z)
  7877. this.maximumWorld.z = v.z;
  7878. }
  7879. // OBB
  7880. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7881. this.center.scaleInPlace(0.5);
  7882. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7883. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7884. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7885. this._worldMatrix = world;
  7886. };
  7887. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7888. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7889. };
  7890. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7891. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7892. };
  7893. BoundingBox.prototype.intersectsPoint = function (point) {
  7894. var delta = -BABYLON.Epsilon;
  7895. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7896. return false;
  7897. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7898. return false;
  7899. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7900. return false;
  7901. return true;
  7902. };
  7903. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7904. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7905. };
  7906. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7907. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7908. return false;
  7909. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7910. return false;
  7911. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7912. return false;
  7913. return true;
  7914. };
  7915. // Statics
  7916. BoundingBox.Intersects = function (box0, box1) {
  7917. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7918. return false;
  7919. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7920. return false;
  7921. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7922. return false;
  7923. return true;
  7924. };
  7925. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7926. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7927. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7928. return (num <= (sphereRadius * sphereRadius));
  7929. };
  7930. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7931. for (var p = 0; p < 6; p++) {
  7932. for (var i = 0; i < 8; i++) {
  7933. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7934. return false;
  7935. }
  7936. }
  7937. }
  7938. return true;
  7939. };
  7940. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7941. for (var p = 0; p < 6; p++) {
  7942. var inCount = 8;
  7943. for (var i = 0; i < 8; i++) {
  7944. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7945. --inCount;
  7946. }
  7947. else {
  7948. break;
  7949. }
  7950. }
  7951. if (inCount === 0)
  7952. return false;
  7953. }
  7954. return true;
  7955. };
  7956. return BoundingBox;
  7957. })();
  7958. BABYLON.BoundingBox = BoundingBox;
  7959. })(BABYLON || (BABYLON = {}));
  7960. var BABYLON;
  7961. (function (BABYLON) {
  7962. var computeBoxExtents = function (axis, box) {
  7963. var p = BABYLON.Vector3.Dot(box.center, axis);
  7964. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7965. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7966. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7967. var r = r0 + r1 + r2;
  7968. return {
  7969. min: p - r,
  7970. max: p + r
  7971. };
  7972. };
  7973. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7974. var axisOverlap = function (axis, box0, box1) {
  7975. var result0 = computeBoxExtents(axis, box0);
  7976. var result1 = computeBoxExtents(axis, box1);
  7977. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7978. };
  7979. var BoundingInfo = (function () {
  7980. function BoundingInfo(minimum, maximum) {
  7981. this.minimum = minimum;
  7982. this.maximum = maximum;
  7983. this._isLocked = false;
  7984. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7985. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7986. }
  7987. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7988. get: function () {
  7989. return this._isLocked;
  7990. },
  7991. set: function (value) {
  7992. this._isLocked = value;
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. // Methods
  7998. BoundingInfo.prototype.update = function (world) {
  7999. if (this._isLocked) {
  8000. return;
  8001. }
  8002. this.boundingBox._update(world);
  8003. this.boundingSphere._update(world);
  8004. };
  8005. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8006. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8007. return false;
  8008. return this.boundingBox.isInFrustum(frustumPlanes);
  8009. };
  8010. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8011. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8012. };
  8013. BoundingInfo.prototype._checkCollision = function (collider) {
  8014. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8015. };
  8016. BoundingInfo.prototype.intersectsPoint = function (point) {
  8017. if (!this.boundingSphere.centerWorld) {
  8018. return false;
  8019. }
  8020. if (!this.boundingSphere.intersectsPoint(point)) {
  8021. return false;
  8022. }
  8023. if (!this.boundingBox.intersectsPoint(point)) {
  8024. return false;
  8025. }
  8026. return true;
  8027. };
  8028. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8029. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8030. return false;
  8031. }
  8032. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8033. return false;
  8034. }
  8035. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8036. return false;
  8037. }
  8038. if (!precise) {
  8039. return true;
  8040. }
  8041. var box0 = this.boundingBox;
  8042. var box1 = boundingInfo.boundingBox;
  8043. if (!axisOverlap(box0.directions[0], box0, box1))
  8044. return false;
  8045. if (!axisOverlap(box0.directions[1], box0, box1))
  8046. return false;
  8047. if (!axisOverlap(box0.directions[2], box0, box1))
  8048. return false;
  8049. if (!axisOverlap(box1.directions[0], box0, box1))
  8050. return false;
  8051. if (!axisOverlap(box1.directions[1], box0, box1))
  8052. return false;
  8053. if (!axisOverlap(box1.directions[2], box0, box1))
  8054. return false;
  8055. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8056. return false;
  8057. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8058. return false;
  8059. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8060. return false;
  8061. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8062. return false;
  8063. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8064. return false;
  8065. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8066. return false;
  8067. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8068. return false;
  8069. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8070. return false;
  8071. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8072. return false;
  8073. return true;
  8074. };
  8075. return BoundingInfo;
  8076. })();
  8077. BABYLON.BoundingInfo = BoundingInfo;
  8078. })(BABYLON || (BABYLON = {}));
  8079. var BABYLON;
  8080. (function (BABYLON) {
  8081. var Ray = (function () {
  8082. function Ray(origin, direction, length) {
  8083. if (length === void 0) { length = Number.MAX_VALUE; }
  8084. this.origin = origin;
  8085. this.direction = direction;
  8086. this.length = length;
  8087. }
  8088. // Methods
  8089. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8090. var d = 0.0;
  8091. var maxValue = Number.MAX_VALUE;
  8092. var inv;
  8093. var min;
  8094. var max;
  8095. var temp;
  8096. if (Math.abs(this.direction.x) < 0.0000001) {
  8097. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8098. return false;
  8099. }
  8100. }
  8101. else {
  8102. inv = 1.0 / this.direction.x;
  8103. min = (minimum.x - this.origin.x) * inv;
  8104. max = (maximum.x - this.origin.x) * inv;
  8105. if (max === -Infinity) {
  8106. max = Infinity;
  8107. }
  8108. if (min > max) {
  8109. temp = min;
  8110. min = max;
  8111. max = temp;
  8112. }
  8113. d = Math.max(min, d);
  8114. maxValue = Math.min(max, maxValue);
  8115. if (d > maxValue) {
  8116. return false;
  8117. }
  8118. }
  8119. if (Math.abs(this.direction.y) < 0.0000001) {
  8120. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8121. return false;
  8122. }
  8123. }
  8124. else {
  8125. inv = 1.0 / this.direction.y;
  8126. min = (minimum.y - this.origin.y) * inv;
  8127. max = (maximum.y - this.origin.y) * inv;
  8128. if (max === -Infinity) {
  8129. max = Infinity;
  8130. }
  8131. if (min > max) {
  8132. temp = min;
  8133. min = max;
  8134. max = temp;
  8135. }
  8136. d = Math.max(min, d);
  8137. maxValue = Math.min(max, maxValue);
  8138. if (d > maxValue) {
  8139. return false;
  8140. }
  8141. }
  8142. if (Math.abs(this.direction.z) < 0.0000001) {
  8143. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8144. return false;
  8145. }
  8146. }
  8147. else {
  8148. inv = 1.0 / this.direction.z;
  8149. min = (minimum.z - this.origin.z) * inv;
  8150. max = (maximum.z - this.origin.z) * inv;
  8151. if (max === -Infinity) {
  8152. max = Infinity;
  8153. }
  8154. if (min > max) {
  8155. temp = min;
  8156. min = max;
  8157. max = temp;
  8158. }
  8159. d = Math.max(min, d);
  8160. maxValue = Math.min(max, maxValue);
  8161. if (d > maxValue) {
  8162. return false;
  8163. }
  8164. }
  8165. return true;
  8166. };
  8167. Ray.prototype.intersectsBox = function (box) {
  8168. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8169. };
  8170. Ray.prototype.intersectsSphere = function (sphere) {
  8171. var x = sphere.center.x - this.origin.x;
  8172. var y = sphere.center.y - this.origin.y;
  8173. var z = sphere.center.z - this.origin.z;
  8174. var pyth = (x * x) + (y * y) + (z * z);
  8175. var rr = sphere.radius * sphere.radius;
  8176. if (pyth <= rr) {
  8177. return true;
  8178. }
  8179. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8180. if (dot < 0.0) {
  8181. return false;
  8182. }
  8183. var temp = pyth - (dot * dot);
  8184. return temp <= rr;
  8185. };
  8186. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8187. if (!this._edge1) {
  8188. this._edge1 = BABYLON.Vector3.Zero();
  8189. this._edge2 = BABYLON.Vector3.Zero();
  8190. this._pvec = BABYLON.Vector3.Zero();
  8191. this._tvec = BABYLON.Vector3.Zero();
  8192. this._qvec = BABYLON.Vector3.Zero();
  8193. }
  8194. vertex1.subtractToRef(vertex0, this._edge1);
  8195. vertex2.subtractToRef(vertex0, this._edge2);
  8196. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8197. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8198. if (det === 0) {
  8199. return null;
  8200. }
  8201. var invdet = 1 / det;
  8202. this.origin.subtractToRef(vertex0, this._tvec);
  8203. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8204. if (bu < 0 || bu > 1.0) {
  8205. return null;
  8206. }
  8207. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8208. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8209. if (bv < 0 || bu + bv > 1.0) {
  8210. return null;
  8211. }
  8212. //check if the distance is longer than the predefined length.
  8213. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8214. if (distance > this.length) {
  8215. return null;
  8216. }
  8217. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8218. };
  8219. Ray.prototype.intersectsPlane = function (plane) {
  8220. var distance;
  8221. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8222. if (Math.abs(result1) < 9.99999997475243E-07) {
  8223. return null;
  8224. }
  8225. else {
  8226. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8227. distance = (-plane.d - result2) / result1;
  8228. if (distance < 0.0) {
  8229. if (distance < -9.99999997475243E-07) {
  8230. return null;
  8231. }
  8232. else {
  8233. return 0;
  8234. }
  8235. }
  8236. return distance;
  8237. }
  8238. };
  8239. /**
  8240. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8241. * @param sega the first point of the segment to test the intersection against
  8242. * @param segb the second point of the segment to test the intersection against
  8243. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8244. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8245. */
  8246. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8247. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8248. var u = segb.subtract(sega);
  8249. var v = rsegb.subtract(this.origin);
  8250. var w = sega.subtract(this.origin);
  8251. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8252. var b = BABYLON.Vector3.Dot(u, v);
  8253. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8254. var d = BABYLON.Vector3.Dot(u, w);
  8255. var e = BABYLON.Vector3.Dot(v, w);
  8256. var D = a * c - b * b; // always >= 0
  8257. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8258. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8259. // compute the line parameters of the two closest points
  8260. if (D < Ray.smallnum) {
  8261. sN = 0.0; // force using point P0 on segment S1
  8262. sD = 1.0; // to prevent possible division by 0.0 later
  8263. tN = e;
  8264. tD = c;
  8265. }
  8266. else {
  8267. sN = (b * e - c * d);
  8268. tN = (a * e - b * d);
  8269. if (sN < 0.0) {
  8270. sN = 0.0;
  8271. tN = e;
  8272. tD = c;
  8273. }
  8274. else if (sN > sD) {
  8275. sN = sD;
  8276. tN = e + b;
  8277. tD = c;
  8278. }
  8279. }
  8280. if (tN < 0.0) {
  8281. tN = 0.0;
  8282. // recompute sc for this edge
  8283. if (-d < 0.0) {
  8284. sN = 0.0;
  8285. }
  8286. else if (-d > a)
  8287. sN = sD;
  8288. else {
  8289. sN = -d;
  8290. sD = a;
  8291. }
  8292. }
  8293. else if (tN > tD) {
  8294. tN = tD;
  8295. // recompute sc for this edge
  8296. if ((-d + b) < 0.0) {
  8297. sN = 0;
  8298. }
  8299. else if ((-d + b) > a) {
  8300. sN = sD;
  8301. }
  8302. else {
  8303. sN = (-d + b);
  8304. sD = a;
  8305. }
  8306. }
  8307. // finally do the division to get sc and tc
  8308. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8309. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8310. // get the difference of the two closest points
  8311. var qtc = v.multiplyByFloats(tc, tc, tc);
  8312. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8313. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8314. if (isIntersected) {
  8315. return qtc.length();
  8316. }
  8317. return -1;
  8318. };
  8319. // Statics
  8320. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8321. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8322. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8323. var direction = end.subtract(start);
  8324. direction.normalize();
  8325. return new Ray(start, direction);
  8326. };
  8327. /**
  8328. * 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
  8329. * transformed to the given world matrix.
  8330. * @param origin The origin point
  8331. * @param end The end point
  8332. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8333. */
  8334. Ray.CreateNewFromTo = function (origin, end, world) {
  8335. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8336. var direction = end.subtract(origin);
  8337. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8338. direction.normalize();
  8339. return Ray.Transform(new Ray(origin, direction, length), world);
  8340. };
  8341. Ray.Transform = function (ray, matrix) {
  8342. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8343. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8344. newDirection.normalize();
  8345. return new Ray(newOrigin, newDirection, ray.length);
  8346. };
  8347. Ray.smallnum = 0.00000001;
  8348. Ray.rayl = 10e8;
  8349. return Ray;
  8350. })();
  8351. BABYLON.Ray = Ray;
  8352. })(BABYLON || (BABYLON = {}));
  8353. var BABYLON;
  8354. (function (BABYLON) {
  8355. var AbstractMesh = (function (_super) {
  8356. __extends(AbstractMesh, _super);
  8357. // Constructor
  8358. function AbstractMesh(name, scene) {
  8359. var _this = this;
  8360. _super.call(this, name, scene);
  8361. // Events
  8362. /**
  8363. * An event triggered when this mesh collides with another one
  8364. * @type {BABYLON.Observable}
  8365. */
  8366. this.onCollideObservable = new BABYLON.Observable();
  8367. /**
  8368. * An event triggered when the collision's position changes
  8369. * @type {BABYLON.Observable}
  8370. */
  8371. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8372. /**
  8373. * An event triggered after the world matrix is updated
  8374. * @type {BABYLON.Observable}
  8375. */
  8376. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8377. // Properties
  8378. this.definedFacingForward = true; // orientation for POV movement & rotation
  8379. this.position = new BABYLON.Vector3(0, 0, 0);
  8380. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8381. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8382. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8383. this.visibility = 1.0;
  8384. this.alphaIndex = Number.MAX_VALUE;
  8385. this.infiniteDistance = false;
  8386. this.isVisible = true;
  8387. this.isPickable = true;
  8388. this.showBoundingBox = false;
  8389. this.showSubMeshesBoundingBox = false;
  8390. this.onDispose = null;
  8391. this.isBlocker = false;
  8392. this.renderingGroupId = 0;
  8393. this.receiveShadows = false;
  8394. this.renderOutline = false;
  8395. this.outlineColor = BABYLON.Color3.Red();
  8396. this.outlineWidth = 0.02;
  8397. this.renderOverlay = false;
  8398. this.overlayColor = BABYLON.Color3.Red();
  8399. this.overlayAlpha = 0.5;
  8400. this.hasVertexAlpha = false;
  8401. this.useVertexColors = true;
  8402. this.applyFog = true;
  8403. this.computeBonesUsingShaders = true;
  8404. this.scalingDeterminant = 1;
  8405. this.numBoneInfluencers = 4;
  8406. this.useOctreeForRenderingSelection = true;
  8407. this.useOctreeForPicking = true;
  8408. this.useOctreeForCollisions = true;
  8409. this.layerMask = 0x0FFFFFFF;
  8410. this.alwaysSelectAsActiveMesh = false;
  8411. // Collisions
  8412. this._checkCollisions = false;
  8413. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8414. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8415. this._collider = new BABYLON.Collider();
  8416. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8417. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8418. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8419. // Edges
  8420. this.edgesWidth = 1;
  8421. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8422. // Cache
  8423. this._localWorld = BABYLON.Matrix.Zero();
  8424. this._worldMatrix = BABYLON.Matrix.Zero();
  8425. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8426. this._absolutePosition = BABYLON.Vector3.Zero();
  8427. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8428. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8429. this._isDirty = false;
  8430. this._pivotMatrix = BABYLON.Matrix.Identity();
  8431. this._isDisposed = false;
  8432. this._renderId = 0;
  8433. this._intersectionsInProgress = new Array();
  8434. this._isWorldMatrixFrozen = false;
  8435. this._unIndexed = false;
  8436. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8437. if (collidedMesh === void 0) { collidedMesh = null; }
  8438. //TODO move this to the collision coordinator!
  8439. if (_this.getScene().workerCollisions)
  8440. newPosition.multiplyInPlace(_this._collider.radius);
  8441. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8442. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8443. _this.position.addInPlace(_this._diffPositionForCollisions);
  8444. }
  8445. if (collidedMesh) {
  8446. _this.onCollideObservable.notifyObservers(collidedMesh);
  8447. }
  8448. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8449. };
  8450. scene.addMesh(this);
  8451. }
  8452. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8453. get: function () {
  8454. return AbstractMesh._BILLBOARDMODE_NONE;
  8455. },
  8456. enumerable: true,
  8457. configurable: true
  8458. });
  8459. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8460. get: function () {
  8461. return AbstractMesh._BILLBOARDMODE_X;
  8462. },
  8463. enumerable: true,
  8464. configurable: true
  8465. });
  8466. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8467. get: function () {
  8468. return AbstractMesh._BILLBOARDMODE_Y;
  8469. },
  8470. enumerable: true,
  8471. configurable: true
  8472. });
  8473. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8474. get: function () {
  8475. return AbstractMesh._BILLBOARDMODE_Z;
  8476. },
  8477. enumerable: true,
  8478. configurable: true
  8479. });
  8480. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8481. get: function () {
  8482. return AbstractMesh._BILLBOARDMODE_ALL;
  8483. },
  8484. enumerable: true,
  8485. configurable: true
  8486. });
  8487. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8488. set: function (callback) {
  8489. if (this._onCollideObserver) {
  8490. this.onCollideObservable.remove(this._onCollideObserver);
  8491. }
  8492. this._onCollideObserver = this.onCollideObservable.add(callback);
  8493. },
  8494. enumerable: true,
  8495. configurable: true
  8496. });
  8497. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8498. set: function (callback) {
  8499. if (this._onCollisionPositionChangeObserver) {
  8500. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8501. }
  8502. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8503. },
  8504. enumerable: true,
  8505. configurable: true
  8506. });
  8507. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8508. get: function () {
  8509. return this._skeleton;
  8510. },
  8511. set: function (value) {
  8512. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8513. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8514. }
  8515. if (value && value.needInitialSkinMatrix) {
  8516. value._registerMeshWithPoseMatrix(this);
  8517. }
  8518. this._skeleton = value;
  8519. if (!this._skeleton) {
  8520. this._bonesTransformMatrices = null;
  8521. }
  8522. },
  8523. enumerable: true,
  8524. configurable: true
  8525. });
  8526. /**
  8527. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8528. */
  8529. AbstractMesh.prototype.toString = function (fullDetails) {
  8530. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8531. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8532. if (this._skeleton) {
  8533. ret += ", skeleton: " + this._skeleton.name;
  8534. }
  8535. if (fullDetails) {
  8536. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8537. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8538. }
  8539. return ret;
  8540. };
  8541. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8542. /**
  8543. * Getting the rotation object.
  8544. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8545. */
  8546. get: function () {
  8547. return this._rotation;
  8548. },
  8549. set: function (newRotation) {
  8550. this._rotation = newRotation;
  8551. },
  8552. enumerable: true,
  8553. configurable: true
  8554. });
  8555. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8556. get: function () {
  8557. return this._scaling;
  8558. },
  8559. set: function (newScaling) {
  8560. this._scaling = newScaling;
  8561. if (this.physicsImpostor) {
  8562. this.physicsImpostor.forceUpdate();
  8563. }
  8564. },
  8565. enumerable: true,
  8566. configurable: true
  8567. });
  8568. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8569. get: function () {
  8570. return this._rotationQuaternion;
  8571. },
  8572. set: function (quaternion) {
  8573. this._rotationQuaternion = quaternion;
  8574. //reset the rotation vector.
  8575. if (quaternion && this.rotation.length()) {
  8576. this.rotation.copyFromFloats(0, 0, 0);
  8577. }
  8578. },
  8579. enumerable: true,
  8580. configurable: true
  8581. });
  8582. // Methods
  8583. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8584. this._poseMatrix.copyFrom(matrix);
  8585. };
  8586. AbstractMesh.prototype.getPoseMatrix = function () {
  8587. return this._poseMatrix;
  8588. };
  8589. AbstractMesh.prototype.disableEdgesRendering = function () {
  8590. if (this._edgesRenderer !== undefined) {
  8591. this._edgesRenderer.dispose();
  8592. this._edgesRenderer = undefined;
  8593. }
  8594. };
  8595. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8596. if (epsilon === void 0) { epsilon = 0.95; }
  8597. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8598. this.disableEdgesRendering();
  8599. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8600. };
  8601. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8602. get: function () {
  8603. return false;
  8604. },
  8605. enumerable: true,
  8606. configurable: true
  8607. });
  8608. AbstractMesh.prototype.getLOD = function (camera) {
  8609. return this;
  8610. };
  8611. AbstractMesh.prototype.getTotalVertices = function () {
  8612. return 0;
  8613. };
  8614. AbstractMesh.prototype.getIndices = function () {
  8615. return null;
  8616. };
  8617. AbstractMesh.prototype.getVerticesData = function (kind) {
  8618. return null;
  8619. };
  8620. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8621. return false;
  8622. };
  8623. AbstractMesh.prototype.getBoundingInfo = function () {
  8624. if (this._masterMesh) {
  8625. return this._masterMesh.getBoundingInfo();
  8626. }
  8627. if (!this._boundingInfo) {
  8628. this._updateBoundingInfo();
  8629. }
  8630. return this._boundingInfo;
  8631. };
  8632. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8633. get: function () {
  8634. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8635. },
  8636. enumerable: true,
  8637. configurable: true
  8638. });
  8639. AbstractMesh.prototype._preActivate = function () {
  8640. };
  8641. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8642. };
  8643. AbstractMesh.prototype._activate = function (renderId) {
  8644. this._renderId = renderId;
  8645. };
  8646. AbstractMesh.prototype.getWorldMatrix = function () {
  8647. if (this._masterMesh) {
  8648. return this._masterMesh.getWorldMatrix();
  8649. }
  8650. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8651. this.computeWorldMatrix();
  8652. }
  8653. return this._worldMatrix;
  8654. };
  8655. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8656. get: function () {
  8657. return this._worldMatrix;
  8658. },
  8659. enumerable: true,
  8660. configurable: true
  8661. });
  8662. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8663. get: function () {
  8664. return this._absolutePosition;
  8665. },
  8666. enumerable: true,
  8667. configurable: true
  8668. });
  8669. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8670. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8671. this.computeWorldMatrix(true);
  8672. this._isWorldMatrixFrozen = true;
  8673. };
  8674. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8675. this._isWorldMatrixFrozen = false;
  8676. this.computeWorldMatrix(true);
  8677. };
  8678. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8679. get: function () {
  8680. return this._isWorldMatrixFrozen;
  8681. },
  8682. enumerable: true,
  8683. configurable: true
  8684. });
  8685. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8686. axis.normalize();
  8687. if (!this.rotationQuaternion) {
  8688. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8689. this.rotation = BABYLON.Vector3.Zero();
  8690. }
  8691. var rotationQuaternion;
  8692. if (!space || space === BABYLON.Space.LOCAL) {
  8693. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8694. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8695. }
  8696. else {
  8697. if (this.parent) {
  8698. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8699. invertParentWorldMatrix.invert();
  8700. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8701. }
  8702. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8703. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8704. }
  8705. };
  8706. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8707. var displacementVector = axis.scale(distance);
  8708. if (!space || space === BABYLON.Space.LOCAL) {
  8709. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8710. this.setPositionWithLocalVector(tempV3);
  8711. }
  8712. else {
  8713. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8714. }
  8715. };
  8716. AbstractMesh.prototype.getAbsolutePosition = function () {
  8717. this.computeWorldMatrix();
  8718. return this._absolutePosition;
  8719. };
  8720. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8721. if (!absolutePosition) {
  8722. return;
  8723. }
  8724. var absolutePositionX;
  8725. var absolutePositionY;
  8726. var absolutePositionZ;
  8727. if (absolutePosition.x === undefined) {
  8728. if (arguments.length < 3) {
  8729. return;
  8730. }
  8731. absolutePositionX = arguments[0];
  8732. absolutePositionY = arguments[1];
  8733. absolutePositionZ = arguments[2];
  8734. }
  8735. else {
  8736. absolutePositionX = absolutePosition.x;
  8737. absolutePositionY = absolutePosition.y;
  8738. absolutePositionZ = absolutePosition.z;
  8739. }
  8740. if (this.parent) {
  8741. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8742. invertParentWorldMatrix.invert();
  8743. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8744. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8745. }
  8746. else {
  8747. this.position.x = absolutePositionX;
  8748. this.position.y = absolutePositionY;
  8749. this.position.z = absolutePositionZ;
  8750. }
  8751. };
  8752. // ================================== Point of View Movement =================================
  8753. /**
  8754. * Perform relative position change from the point of view of behind the front of the mesh.
  8755. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8756. * Supports definition of mesh facing forward or backward.
  8757. * @param {number} amountRight
  8758. * @param {number} amountUp
  8759. * @param {number} amountForward
  8760. */
  8761. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8762. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8763. };
  8764. /**
  8765. * Calculate relative position change from the point of view of behind the front of the mesh.
  8766. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8767. * Supports definition of mesh facing forward or backward.
  8768. * @param {number} amountRight
  8769. * @param {number} amountUp
  8770. * @param {number} amountForward
  8771. */
  8772. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8773. var rotMatrix = new BABYLON.Matrix();
  8774. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8775. rotQuaternion.toRotationMatrix(rotMatrix);
  8776. var translationDelta = BABYLON.Vector3.Zero();
  8777. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8779. return translationDelta;
  8780. };
  8781. // ================================== Point of View Rotation =================================
  8782. /**
  8783. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8784. * Supports definition of mesh facing forward or backward.
  8785. * @param {number} flipBack
  8786. * @param {number} twirlClockwise
  8787. * @param {number} tiltRight
  8788. */
  8789. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8790. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8791. };
  8792. /**
  8793. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8794. * Supports definition of mesh facing forward or backward.
  8795. * @param {number} flipBack
  8796. * @param {number} twirlClockwise
  8797. * @param {number} tiltRight
  8798. */
  8799. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8800. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8801. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8802. };
  8803. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8804. this._pivotMatrix = matrix;
  8805. this._cache.pivotMatrixUpdated = true;
  8806. };
  8807. AbstractMesh.prototype.getPivotMatrix = function () {
  8808. return this._pivotMatrix;
  8809. };
  8810. AbstractMesh.prototype._isSynchronized = function () {
  8811. if (this._isDirty) {
  8812. return false;
  8813. }
  8814. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8815. return false;
  8816. if (this._cache.pivotMatrixUpdated) {
  8817. return false;
  8818. }
  8819. if (this.infiniteDistance) {
  8820. return false;
  8821. }
  8822. if (!this._cache.position.equals(this.position))
  8823. return false;
  8824. if (this.rotationQuaternion) {
  8825. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8826. return false;
  8827. }
  8828. else {
  8829. if (!this._cache.rotation.equals(this.rotation))
  8830. return false;
  8831. }
  8832. if (!this._cache.scaling.equals(this.scaling))
  8833. return false;
  8834. return true;
  8835. };
  8836. AbstractMesh.prototype._initCache = function () {
  8837. _super.prototype._initCache.call(this);
  8838. this._cache.localMatrixUpdated = false;
  8839. this._cache.position = BABYLON.Vector3.Zero();
  8840. this._cache.scaling = BABYLON.Vector3.Zero();
  8841. this._cache.rotation = BABYLON.Vector3.Zero();
  8842. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8843. this._cache.billboardMode = -1;
  8844. };
  8845. AbstractMesh.prototype.markAsDirty = function (property) {
  8846. if (property === "rotation") {
  8847. this.rotationQuaternion = null;
  8848. }
  8849. this._currentRenderId = Number.MAX_VALUE;
  8850. this._isDirty = true;
  8851. };
  8852. AbstractMesh.prototype._updateBoundingInfo = function () {
  8853. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8854. this._boundingInfo.update(this.worldMatrixFromCache);
  8855. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8856. };
  8857. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8858. if (!this.subMeshes) {
  8859. return;
  8860. }
  8861. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8862. var subMesh = this.subMeshes[subIndex];
  8863. if (!subMesh.IsGlobal) {
  8864. subMesh.updateBoundingInfo(matrix);
  8865. }
  8866. }
  8867. };
  8868. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8869. if (this._isWorldMatrixFrozen) {
  8870. return this._worldMatrix;
  8871. }
  8872. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8873. this._currentRenderId = this.getScene().getRenderId();
  8874. return this._worldMatrix;
  8875. }
  8876. this._cache.position.copyFrom(this.position);
  8877. this._cache.scaling.copyFrom(this.scaling);
  8878. this._cache.pivotMatrixUpdated = false;
  8879. this._cache.billboardMode = this.billboardMode;
  8880. this._currentRenderId = this.getScene().getRenderId();
  8881. this._isDirty = false;
  8882. // Scaling
  8883. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8884. // Rotation
  8885. //rotate, if quaternion is set and rotation was used
  8886. if (this.rotationQuaternion) {
  8887. var len = this.rotation.length();
  8888. if (len) {
  8889. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8890. this.rotation.copyFromFloats(0, 0, 0);
  8891. }
  8892. }
  8893. if (this.rotationQuaternion) {
  8894. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8895. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8896. }
  8897. else {
  8898. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8899. this._cache.rotation.copyFrom(this.rotation);
  8900. }
  8901. // Translation
  8902. if (this.infiniteDistance && !this.parent) {
  8903. var camera = this.getScene().activeCamera;
  8904. if (camera) {
  8905. var cameraWorldMatrix = camera.getWorldMatrix();
  8906. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8907. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8908. }
  8909. }
  8910. else {
  8911. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8912. }
  8913. // Composing transformations
  8914. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8915. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8916. // Billboarding
  8917. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8918. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8919. var localPosition = BABYLON.Tmp.Vector3[0];
  8920. if (this.parent && this.parent.getWorldMatrix) {
  8921. this._markSyncedWithParent();
  8922. var parentMatrix;
  8923. if (this._meshToBoneReferal) {
  8924. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8925. parentMatrix = BABYLON.Tmp.Matrix[6];
  8926. }
  8927. else {
  8928. parentMatrix = this.parent.getWorldMatrix();
  8929. }
  8930. BABYLON.Vector3.TransformCoordinatesToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  8931. localPosition = BABYLON.Tmp.Vector3[1];
  8932. }
  8933. var zero = this.getScene().activeCamera.globalPosition.clone();
  8934. if (this.parent && this.parent.position) {
  8935. localPosition.addInPlace(this.parent.position);
  8936. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8937. }
  8938. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8939. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8940. zero.x = localPosition.x + BABYLON.Epsilon;
  8941. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8942. zero.y = localPosition.y + BABYLON.Epsilon;
  8943. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8944. zero.z = localPosition.z + BABYLON.Epsilon;
  8945. }
  8946. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8947. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8948. BABYLON.Tmp.Matrix[3].invert();
  8949. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8950. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8951. }
  8952. // Local world
  8953. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8954. // Parent
  8955. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8956. this._markSyncedWithParent();
  8957. if (this._meshToBoneReferal) {
  8958. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8959. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8960. }
  8961. else {
  8962. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8963. }
  8964. }
  8965. else {
  8966. this._worldMatrix.copyFrom(this._localWorld);
  8967. }
  8968. // Bounding info
  8969. this._updateBoundingInfo();
  8970. // Absolute position
  8971. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8972. // Callbacks
  8973. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  8974. if (!this._poseMatrix) {
  8975. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8976. }
  8977. return this._worldMatrix;
  8978. };
  8979. /**
  8980. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8981. * @param func: callback function to add
  8982. */
  8983. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8984. this.onAfterWorldMatrixUpdateObservable.add(func);
  8985. };
  8986. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8987. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  8988. };
  8989. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8990. this.computeWorldMatrix();
  8991. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8992. };
  8993. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8994. this.computeWorldMatrix();
  8995. var invLocalWorldMatrix = this._localWorld.clone();
  8996. invLocalWorldMatrix.invert();
  8997. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8998. };
  8999. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9000. this.computeWorldMatrix(true);
  9001. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9002. };
  9003. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9004. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9005. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9006. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9007. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9008. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9009. /// <returns>Mesh oriented towards targetMesh</returns>
  9010. yawCor = yawCor || 0; // default to zero if undefined
  9011. pitchCor = pitchCor || 0;
  9012. rollCor = rollCor || 0;
  9013. var dv = targetPoint.subtract(this.position);
  9014. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9015. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9016. var pitch = Math.atan2(dv.y, len);
  9017. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9018. };
  9019. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9020. this._meshToBoneReferal = affectedMesh;
  9021. this.parent = bone;
  9022. if (bone.getWorldMatrix().determinant() < 0) {
  9023. this.scalingDeterminant *= -1;
  9024. }
  9025. };
  9026. AbstractMesh.prototype.detachFromBone = function () {
  9027. if (this.parent.getWorldMatrix().determinant() < 0) {
  9028. this.scalingDeterminant *= -1;
  9029. }
  9030. this._meshToBoneReferal = null;
  9031. this.parent = null;
  9032. };
  9033. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9034. return this._boundingInfo.isInFrustum(frustumPlanes);
  9035. };
  9036. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9037. if (!camera) {
  9038. camera = this.getScene().activeCamera;
  9039. }
  9040. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9041. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9042. return false;
  9043. }
  9044. return true;
  9045. };
  9046. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9047. if (!this._boundingInfo || !mesh._boundingInfo) {
  9048. return false;
  9049. }
  9050. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9051. };
  9052. AbstractMesh.prototype.intersectsPoint = function (point) {
  9053. if (!this._boundingInfo) {
  9054. return false;
  9055. }
  9056. return this._boundingInfo.intersectsPoint(point);
  9057. };
  9058. // Physics
  9059. /**
  9060. * @Deprecated. Use new PhysicsImpostor instead.
  9061. * */
  9062. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9063. //legacy support
  9064. if (impostor.impostor) {
  9065. options = impostor;
  9066. impostor = impostor.impostor;
  9067. }
  9068. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9069. return this.physicsImpostor.physicsBody;
  9070. };
  9071. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9072. return this.physicsImpostor;
  9073. };
  9074. /**
  9075. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9076. */
  9077. AbstractMesh.prototype.getPhysicsMass = function () {
  9078. return this.physicsImpostor.getParam("mass");
  9079. };
  9080. /**
  9081. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9082. */
  9083. AbstractMesh.prototype.getPhysicsFriction = function () {
  9084. return this.physicsImpostor.getParam("friction");
  9085. };
  9086. /**
  9087. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9088. */
  9089. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9090. return this.physicsImpostor.getParam("resitution");
  9091. };
  9092. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9093. if (!camera) {
  9094. camera = this.getScene().activeCamera;
  9095. }
  9096. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9097. };
  9098. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9099. if (!camera) {
  9100. camera = this.getScene().activeCamera;
  9101. }
  9102. return this.absolutePosition.subtract(camera.position).length();
  9103. };
  9104. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9105. if (!this.physicsImpostor) {
  9106. return;
  9107. }
  9108. this.physicsImpostor.applyImpulse(force, contactPoint);
  9109. };
  9110. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9111. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9112. return;
  9113. }
  9114. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9115. mainPivot: pivot1,
  9116. connectedPivot: pivot2,
  9117. nativeParams: options
  9118. });
  9119. };
  9120. /**
  9121. * @Deprecated
  9122. */
  9123. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9124. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9125. this.updatePhysicsBody();
  9126. };
  9127. /**
  9128. * @Deprecated
  9129. * Calling this function is not needed anymore.
  9130. * The physics engine takes care of transofmration automatically.
  9131. */
  9132. AbstractMesh.prototype.updatePhysicsBody = function () {
  9133. //Unneeded
  9134. };
  9135. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9136. // Collisions
  9137. get: function () {
  9138. return this._checkCollisions;
  9139. },
  9140. set: function (collisionEnabled) {
  9141. this._checkCollisions = collisionEnabled;
  9142. if (this.getScene().workerCollisions) {
  9143. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9144. }
  9145. },
  9146. enumerable: true,
  9147. configurable: true
  9148. });
  9149. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9150. var globalPosition = this.getAbsolutePosition();
  9151. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9152. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9153. this._collider.radius = this.ellipsoid;
  9154. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9155. };
  9156. // Submeshes octree
  9157. /**
  9158. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9159. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9160. */
  9161. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9162. if (maxCapacity === void 0) { maxCapacity = 64; }
  9163. if (maxDepth === void 0) { maxDepth = 2; }
  9164. if (!this._submeshesOctree) {
  9165. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9166. }
  9167. this.computeWorldMatrix(true);
  9168. // Update octree
  9169. var bbox = this.getBoundingInfo().boundingBox;
  9170. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9171. return this._submeshesOctree;
  9172. };
  9173. // Collisions
  9174. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9175. this._generatePointsArray();
  9176. // Transformation
  9177. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9178. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9179. subMesh._lastColliderWorldVertices = [];
  9180. subMesh._trianglePlanes = [];
  9181. var start = subMesh.verticesStart;
  9182. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9183. for (var i = start; i < end; i++) {
  9184. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9185. }
  9186. }
  9187. // Collide
  9188. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9189. if (collider.collisionFound) {
  9190. collider.collidedMesh = this;
  9191. }
  9192. };
  9193. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9194. var subMeshes;
  9195. var len;
  9196. // Octrees
  9197. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9198. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9199. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9200. len = intersections.length;
  9201. subMeshes = intersections.data;
  9202. }
  9203. else {
  9204. subMeshes = this.subMeshes;
  9205. len = subMeshes.length;
  9206. }
  9207. for (var index = 0; index < len; index++) {
  9208. var subMesh = subMeshes[index];
  9209. // Bounding test
  9210. if (len > 1 && !subMesh._checkCollision(collider))
  9211. continue;
  9212. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9213. }
  9214. };
  9215. AbstractMesh.prototype._checkCollision = function (collider) {
  9216. // Bounding box test
  9217. if (!this._boundingInfo._checkCollision(collider))
  9218. return;
  9219. // Transformation matrix
  9220. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9221. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9222. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9223. };
  9224. // Picking
  9225. AbstractMesh.prototype._generatePointsArray = function () {
  9226. return false;
  9227. };
  9228. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9229. var pickingInfo = new BABYLON.PickingInfo();
  9230. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9231. return pickingInfo;
  9232. }
  9233. if (!this._generatePointsArray()) {
  9234. return pickingInfo;
  9235. }
  9236. var intersectInfo = null;
  9237. // Octrees
  9238. var subMeshes;
  9239. var len;
  9240. if (this._submeshesOctree && this.useOctreeForPicking) {
  9241. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9242. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9243. len = intersections.length;
  9244. subMeshes = intersections.data;
  9245. }
  9246. else {
  9247. subMeshes = this.subMeshes;
  9248. len = subMeshes.length;
  9249. }
  9250. for (var index = 0; index < len; index++) {
  9251. var subMesh = subMeshes[index];
  9252. // Bounding test
  9253. if (len > 1 && !subMesh.canIntersects(ray))
  9254. continue;
  9255. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9256. if (currentIntersectInfo) {
  9257. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9258. intersectInfo = currentIntersectInfo;
  9259. intersectInfo.subMeshId = index;
  9260. if (fastCheck) {
  9261. break;
  9262. }
  9263. }
  9264. }
  9265. }
  9266. if (intersectInfo) {
  9267. // Get picked point
  9268. var world = this.getWorldMatrix();
  9269. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9270. var direction = ray.direction.clone();
  9271. direction = direction.scale(intersectInfo.distance);
  9272. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9273. var pickedPoint = worldOrigin.add(worldDirection);
  9274. // Return result
  9275. pickingInfo.hit = true;
  9276. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9277. pickingInfo.pickedPoint = pickedPoint;
  9278. pickingInfo.pickedMesh = this;
  9279. pickingInfo.bu = intersectInfo.bu;
  9280. pickingInfo.bv = intersectInfo.bv;
  9281. pickingInfo.faceId = intersectInfo.faceId;
  9282. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9283. return pickingInfo;
  9284. }
  9285. return pickingInfo;
  9286. };
  9287. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9288. return null;
  9289. };
  9290. AbstractMesh.prototype.releaseSubMeshes = function () {
  9291. if (this.subMeshes) {
  9292. while (this.subMeshes.length) {
  9293. this.subMeshes[0].dispose();
  9294. }
  9295. }
  9296. else {
  9297. this.subMeshes = new Array();
  9298. }
  9299. };
  9300. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9301. var _this = this;
  9302. var index;
  9303. // Action manager
  9304. if (this.actionManager) {
  9305. this.actionManager.dispose();
  9306. this.actionManager = null;
  9307. }
  9308. // Skeleton
  9309. this.skeleton = null;
  9310. // Animations
  9311. this.getScene().stopAnimation(this);
  9312. // Physics
  9313. if (this.physicsImpostor) {
  9314. this.physicsImpostor.dispose();
  9315. }
  9316. // Intersections in progress
  9317. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9318. var other = this._intersectionsInProgress[index];
  9319. var pos = other._intersectionsInProgress.indexOf(this);
  9320. other._intersectionsInProgress.splice(pos, 1);
  9321. }
  9322. this._intersectionsInProgress = [];
  9323. // Lights
  9324. var lights = this.getScene().lights;
  9325. lights.forEach(function (light) {
  9326. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9327. if (meshIndex !== -1) {
  9328. light.includedOnlyMeshes.splice(meshIndex, 1);
  9329. }
  9330. meshIndex = light.excludedMeshes.indexOf(_this);
  9331. if (meshIndex !== -1) {
  9332. light.excludedMeshes.splice(meshIndex, 1);
  9333. }
  9334. });
  9335. // Edges
  9336. if (this._edgesRenderer) {
  9337. this._edgesRenderer.dispose();
  9338. this._edgesRenderer = null;
  9339. }
  9340. // SubMeshes
  9341. this.releaseSubMeshes();
  9342. // Remove from scene
  9343. this.getScene().removeMesh(this);
  9344. if (!doNotRecurse) {
  9345. // Particles
  9346. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9347. if (this.getScene().particleSystems[index].emitter === this) {
  9348. this.getScene().particleSystems[index].dispose();
  9349. index--;
  9350. }
  9351. }
  9352. // Children
  9353. var objects = this.getDescendants(true);
  9354. for (index = 0; index < objects.length; index++) {
  9355. objects[index].dispose();
  9356. }
  9357. }
  9358. else {
  9359. var childMeshes = this.getChildMeshes(true);
  9360. for (index = 0; index < childMeshes.length; index++) {
  9361. var child = childMeshes[index];
  9362. child.parent = null;
  9363. child.computeWorldMatrix(true);
  9364. }
  9365. }
  9366. _super.prototype.dispose.call(this);
  9367. this.onAfterWorldMatrixUpdateObservable.clear();
  9368. this._isDisposed = true;
  9369. // Callback
  9370. if (this.onDispose) {
  9371. this.onDispose();
  9372. }
  9373. };
  9374. // Statics
  9375. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9376. AbstractMesh._BILLBOARDMODE_X = 1;
  9377. AbstractMesh._BILLBOARDMODE_Y = 2;
  9378. AbstractMesh._BILLBOARDMODE_Z = 4;
  9379. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9380. return AbstractMesh;
  9381. })(BABYLON.Node);
  9382. BABYLON.AbstractMesh = AbstractMesh;
  9383. })(BABYLON || (BABYLON = {}));
  9384. var BABYLON;
  9385. (function (BABYLON) {
  9386. var Light = (function (_super) {
  9387. __extends(Light, _super);
  9388. function Light(name, scene) {
  9389. _super.call(this, name, scene);
  9390. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9391. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9392. this.intensity = 1.0;
  9393. this.range = Number.MAX_VALUE;
  9394. this.includeOnlyWithLayerMask = 0;
  9395. this.includedOnlyMeshes = new Array();
  9396. this.excludedMeshes = new Array();
  9397. this.excludeWithLayerMask = 0;
  9398. // PBR Properties.
  9399. this.radius = 0.00001;
  9400. this._excludedMeshesIds = new Array();
  9401. this._includedOnlyMeshesIds = new Array();
  9402. scene.addLight(this);
  9403. }
  9404. /**
  9405. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9406. */
  9407. Light.prototype.toString = function (fullDetails) {
  9408. var ret = "Name: " + this.name;
  9409. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9410. if (this.animations) {
  9411. for (var i = 0; i < this.animations.length; i++) {
  9412. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9413. }
  9414. }
  9415. if (fullDetails) {
  9416. }
  9417. return ret;
  9418. };
  9419. Light.prototype.getShadowGenerator = function () {
  9420. return this._shadowGenerator;
  9421. };
  9422. Light.prototype.getAbsolutePosition = function () {
  9423. return BABYLON.Vector3.Zero();
  9424. };
  9425. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9426. };
  9427. Light.prototype._getWorldMatrix = function () {
  9428. return BABYLON.Matrix.Identity();
  9429. };
  9430. Light.prototype.canAffectMesh = function (mesh) {
  9431. if (!mesh) {
  9432. return true;
  9433. }
  9434. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9435. return false;
  9436. }
  9437. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9438. return false;
  9439. }
  9440. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9441. return false;
  9442. }
  9443. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9444. return false;
  9445. }
  9446. return true;
  9447. };
  9448. Light.prototype.getWorldMatrix = function () {
  9449. this._currentRenderId = this.getScene().getRenderId();
  9450. var worldMatrix = this._getWorldMatrix();
  9451. if (this.parent && this.parent.getWorldMatrix) {
  9452. if (!this._parentedWorldMatrix) {
  9453. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9454. }
  9455. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9456. this._markSyncedWithParent();
  9457. return this._parentedWorldMatrix;
  9458. }
  9459. return worldMatrix;
  9460. };
  9461. Light.prototype.dispose = function () {
  9462. if (this._shadowGenerator) {
  9463. this._shadowGenerator.dispose();
  9464. this._shadowGenerator = null;
  9465. }
  9466. // Animations
  9467. this.getScene().stopAnimation(this);
  9468. // Remove from scene
  9469. this.getScene().removeLight(this);
  9470. _super.prototype.dispose.call(this);
  9471. };
  9472. Light.prototype.getTypeID = function () {
  9473. return 0;
  9474. };
  9475. Light.prototype.clone = function (name) {
  9476. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9477. };
  9478. Light.prototype.serialize = function () {
  9479. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9480. // Type
  9481. serializationObject.type = this.getTypeID();
  9482. // Parent
  9483. if (this.parent) {
  9484. serializationObject.parentId = this.parent.id;
  9485. }
  9486. // Inclusion / exclusions
  9487. if (this.excludedMeshes.length > 0) {
  9488. serializationObject.excludedMeshesIds = [];
  9489. this.excludedMeshes.forEach(function (mesh) {
  9490. serializationObject.excludedMeshesIds.push(mesh.id);
  9491. });
  9492. }
  9493. if (this.includedOnlyMeshes.length > 0) {
  9494. serializationObject.includedOnlyMeshesIds = [];
  9495. this.includedOnlyMeshes.forEach(function (mesh) {
  9496. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9497. });
  9498. }
  9499. // Animations
  9500. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9501. serializationObject.ranges = this.serializeAnimationRanges();
  9502. return serializationObject;
  9503. };
  9504. Light.GetConstructorFromName = function (type, name, scene) {
  9505. switch (type) {
  9506. case 0:
  9507. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9508. case 1:
  9509. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9510. case 2:
  9511. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9512. case 3:
  9513. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9514. }
  9515. };
  9516. Light.Parse = function (parsedLight, scene) {
  9517. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9518. // Inclusion / exclusions
  9519. if (parsedLight.excludedMeshesIds) {
  9520. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9521. }
  9522. if (parsedLight.includedOnlyMeshesIds) {
  9523. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9524. }
  9525. // Parent
  9526. if (parsedLight.parentId) {
  9527. light._waitingParentId = parsedLight.parentId;
  9528. }
  9529. // Animations
  9530. if (parsedLight.animations) {
  9531. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9532. var parsedAnimation = parsedLight.animations[animationIndex];
  9533. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9534. }
  9535. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9536. }
  9537. if (parsedLight.autoAnimate) {
  9538. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9539. }
  9540. return light;
  9541. };
  9542. __decorate([
  9543. BABYLON.serializeAsColor3()
  9544. ], Light.prototype, "diffuse", void 0);
  9545. __decorate([
  9546. BABYLON.serializeAsColor3()
  9547. ], Light.prototype, "specular", void 0);
  9548. __decorate([
  9549. BABYLON.serialize()
  9550. ], Light.prototype, "intensity", void 0);
  9551. __decorate([
  9552. BABYLON.serialize()
  9553. ], Light.prototype, "range", void 0);
  9554. __decorate([
  9555. BABYLON.serialize()
  9556. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9557. __decorate([
  9558. BABYLON.serialize()
  9559. ], Light.prototype, "excludeWithLayerMask", void 0);
  9560. __decorate([
  9561. BABYLON.serialize()
  9562. ], Light.prototype, "radius", void 0);
  9563. return Light;
  9564. })(BABYLON.Node);
  9565. BABYLON.Light = Light;
  9566. })(BABYLON || (BABYLON = {}));
  9567. var BABYLON;
  9568. (function (BABYLON) {
  9569. var PointLight = (function (_super) {
  9570. __extends(PointLight, _super);
  9571. function PointLight(name, position, scene) {
  9572. _super.call(this, name, scene);
  9573. this.position = position;
  9574. }
  9575. PointLight.prototype.getAbsolutePosition = function () {
  9576. return this.transformedPosition ? this.transformedPosition : this.position;
  9577. };
  9578. PointLight.prototype.computeTransformedPosition = function () {
  9579. if (this.parent && this.parent.getWorldMatrix) {
  9580. if (!this.transformedPosition) {
  9581. this.transformedPosition = BABYLON.Vector3.Zero();
  9582. }
  9583. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9584. return true;
  9585. }
  9586. return false;
  9587. };
  9588. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9589. if (this.parent && this.parent.getWorldMatrix) {
  9590. this.computeTransformedPosition();
  9591. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9592. return;
  9593. }
  9594. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9595. };
  9596. PointLight.prototype.needCube = function () {
  9597. return true;
  9598. };
  9599. PointLight.prototype.supportsVSM = function () {
  9600. return false;
  9601. };
  9602. PointLight.prototype.needRefreshPerFrame = function () {
  9603. return false;
  9604. };
  9605. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9606. switch (faceIndex) {
  9607. case 0:
  9608. return new BABYLON.Vector3(1, 0, 0);
  9609. case 1:
  9610. return new BABYLON.Vector3(-1, 0, 0);
  9611. case 2:
  9612. return new BABYLON.Vector3(0, -1, 0);
  9613. case 3:
  9614. return new BABYLON.Vector3(0, 1, 0);
  9615. case 4:
  9616. return new BABYLON.Vector3(0, 0, 1);
  9617. case 5:
  9618. return new BABYLON.Vector3(0, 0, -1);
  9619. }
  9620. return BABYLON.Vector3.Zero();
  9621. };
  9622. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9623. var activeCamera = this.getScene().activeCamera;
  9624. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9625. };
  9626. PointLight.prototype._getWorldMatrix = function () {
  9627. if (!this._worldMatrix) {
  9628. this._worldMatrix = BABYLON.Matrix.Identity();
  9629. }
  9630. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9631. return this._worldMatrix;
  9632. };
  9633. PointLight.prototype.getTypeID = function () {
  9634. return 0;
  9635. };
  9636. __decorate([
  9637. BABYLON.serializeAsVector3()
  9638. ], PointLight.prototype, "position", void 0);
  9639. return PointLight;
  9640. })(BABYLON.Light);
  9641. BABYLON.PointLight = PointLight;
  9642. })(BABYLON || (BABYLON = {}));
  9643. var BABYLON;
  9644. (function (BABYLON) {
  9645. var SpotLight = (function (_super) {
  9646. __extends(SpotLight, _super);
  9647. function SpotLight(name, position, direction, angle, exponent, scene) {
  9648. _super.call(this, name, scene);
  9649. this.position = position;
  9650. this.direction = direction;
  9651. this.angle = angle;
  9652. this.exponent = exponent;
  9653. }
  9654. SpotLight.prototype.getAbsolutePosition = function () {
  9655. return this.transformedPosition ? this.transformedPosition : this.position;
  9656. };
  9657. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9658. var activeCamera = this.getScene().activeCamera;
  9659. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9660. };
  9661. SpotLight.prototype.needCube = function () {
  9662. return false;
  9663. };
  9664. SpotLight.prototype.supportsVSM = function () {
  9665. return true;
  9666. };
  9667. SpotLight.prototype.needRefreshPerFrame = function () {
  9668. return false;
  9669. };
  9670. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9671. return this.direction;
  9672. };
  9673. SpotLight.prototype.setDirectionToTarget = function (target) {
  9674. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9675. return this.direction;
  9676. };
  9677. SpotLight.prototype.computeTransformedPosition = function () {
  9678. if (this.parent && this.parent.getWorldMatrix) {
  9679. if (!this.transformedPosition) {
  9680. this.transformedPosition = BABYLON.Vector3.Zero();
  9681. }
  9682. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9683. return true;
  9684. }
  9685. return false;
  9686. };
  9687. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9688. var normalizeDirection;
  9689. if (this.parent && this.parent.getWorldMatrix) {
  9690. if (!this._transformedDirection) {
  9691. this._transformedDirection = BABYLON.Vector3.Zero();
  9692. }
  9693. this.computeTransformedPosition();
  9694. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9695. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9696. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9697. }
  9698. else {
  9699. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9700. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9701. }
  9702. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9703. };
  9704. SpotLight.prototype._getWorldMatrix = function () {
  9705. if (!this._worldMatrix) {
  9706. this._worldMatrix = BABYLON.Matrix.Identity();
  9707. }
  9708. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9709. return this._worldMatrix;
  9710. };
  9711. SpotLight.prototype.getTypeID = function () {
  9712. return 2;
  9713. };
  9714. __decorate([
  9715. BABYLON.serializeAsVector3()
  9716. ], SpotLight.prototype, "position", void 0);
  9717. __decorate([
  9718. BABYLON.serializeAsVector3()
  9719. ], SpotLight.prototype, "direction", void 0);
  9720. __decorate([
  9721. BABYLON.serialize()
  9722. ], SpotLight.prototype, "angle", void 0);
  9723. __decorate([
  9724. BABYLON.serialize()
  9725. ], SpotLight.prototype, "exponent", void 0);
  9726. return SpotLight;
  9727. })(BABYLON.Light);
  9728. BABYLON.SpotLight = SpotLight;
  9729. })(BABYLON || (BABYLON = {}));
  9730. var BABYLON;
  9731. (function (BABYLON) {
  9732. var HemisphericLight = (function (_super) {
  9733. __extends(HemisphericLight, _super);
  9734. function HemisphericLight(name, direction, scene) {
  9735. _super.call(this, name, scene);
  9736. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9737. this.direction = direction;
  9738. }
  9739. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9740. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9741. return this.direction;
  9742. };
  9743. HemisphericLight.prototype.getShadowGenerator = function () {
  9744. return null;
  9745. };
  9746. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9747. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9748. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9749. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9750. };
  9751. HemisphericLight.prototype._getWorldMatrix = function () {
  9752. if (!this._worldMatrix) {
  9753. this._worldMatrix = BABYLON.Matrix.Identity();
  9754. }
  9755. return this._worldMatrix;
  9756. };
  9757. HemisphericLight.prototype.getTypeID = function () {
  9758. return 3;
  9759. };
  9760. __decorate([
  9761. BABYLON.serializeAsColor3()
  9762. ], HemisphericLight.prototype, "groundColor", void 0);
  9763. __decorate([
  9764. BABYLON.serializeAsVector3()
  9765. ], HemisphericLight.prototype, "direction", void 0);
  9766. return HemisphericLight;
  9767. })(BABYLON.Light);
  9768. BABYLON.HemisphericLight = HemisphericLight;
  9769. })(BABYLON || (BABYLON = {}));
  9770. var BABYLON;
  9771. (function (BABYLON) {
  9772. var DirectionalLight = (function (_super) {
  9773. __extends(DirectionalLight, _super);
  9774. function DirectionalLight(name, direction, scene) {
  9775. _super.call(this, name, scene);
  9776. this.shadowOrthoScale = 0.5;
  9777. this.autoUpdateExtends = true;
  9778. // Cache
  9779. this._orthoLeft = Number.MAX_VALUE;
  9780. this._orthoRight = Number.MIN_VALUE;
  9781. this._orthoTop = Number.MIN_VALUE;
  9782. this._orthoBottom = Number.MAX_VALUE;
  9783. this.position = direction.scale(-1);
  9784. this.direction = direction;
  9785. }
  9786. DirectionalLight.prototype.getAbsolutePosition = function () {
  9787. return this.transformedPosition ? this.transformedPosition : this.position;
  9788. };
  9789. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9790. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9791. return this.direction;
  9792. };
  9793. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9794. var activeCamera = this.getScene().activeCamera;
  9795. // Check extends
  9796. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9797. var tempVector3 = BABYLON.Vector3.Zero();
  9798. this._orthoLeft = Number.MAX_VALUE;
  9799. this._orthoRight = Number.MIN_VALUE;
  9800. this._orthoTop = Number.MIN_VALUE;
  9801. this._orthoBottom = Number.MAX_VALUE;
  9802. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9803. var mesh = renderList[meshIndex];
  9804. if (!mesh) {
  9805. continue;
  9806. }
  9807. var boundingInfo = mesh.getBoundingInfo();
  9808. if (!boundingInfo) {
  9809. continue;
  9810. }
  9811. var boundingBox = boundingInfo.boundingBox;
  9812. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9813. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9814. if (tempVector3.x < this._orthoLeft)
  9815. this._orthoLeft = tempVector3.x;
  9816. if (tempVector3.y < this._orthoBottom)
  9817. this._orthoBottom = tempVector3.y;
  9818. if (tempVector3.x > this._orthoRight)
  9819. this._orthoRight = tempVector3.x;
  9820. if (tempVector3.y > this._orthoTop)
  9821. this._orthoTop = tempVector3.y;
  9822. }
  9823. }
  9824. }
  9825. var xOffset = this._orthoRight - this._orthoLeft;
  9826. var yOffset = this._orthoTop - this._orthoBottom;
  9827. 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);
  9828. };
  9829. DirectionalLight.prototype.supportsVSM = function () {
  9830. return true;
  9831. };
  9832. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9833. return true;
  9834. };
  9835. DirectionalLight.prototype.needCube = function () {
  9836. return false;
  9837. };
  9838. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9839. return this.direction;
  9840. };
  9841. DirectionalLight.prototype.computeTransformedPosition = function () {
  9842. if (this.parent && this.parent.getWorldMatrix) {
  9843. if (!this.transformedPosition) {
  9844. this.transformedPosition = BABYLON.Vector3.Zero();
  9845. }
  9846. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9847. return true;
  9848. }
  9849. return false;
  9850. };
  9851. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9852. if (this.parent && this.parent.getWorldMatrix) {
  9853. if (!this._transformedDirection) {
  9854. this._transformedDirection = BABYLON.Vector3.Zero();
  9855. }
  9856. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9857. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9858. return;
  9859. }
  9860. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9861. };
  9862. DirectionalLight.prototype._getWorldMatrix = function () {
  9863. if (!this._worldMatrix) {
  9864. this._worldMatrix = BABYLON.Matrix.Identity();
  9865. }
  9866. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9867. return this._worldMatrix;
  9868. };
  9869. DirectionalLight.prototype.getTypeID = function () {
  9870. return 1;
  9871. };
  9872. __decorate([
  9873. BABYLON.serializeAsVector3()
  9874. ], DirectionalLight.prototype, "position", void 0);
  9875. __decorate([
  9876. BABYLON.serializeAsVector3()
  9877. ], DirectionalLight.prototype, "direction", void 0);
  9878. __decorate([
  9879. BABYLON.serialize()
  9880. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9881. __decorate([
  9882. BABYLON.serialize()
  9883. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9884. return DirectionalLight;
  9885. })(BABYLON.Light);
  9886. BABYLON.DirectionalLight = DirectionalLight;
  9887. })(BABYLON || (BABYLON = {}));
  9888. var BABYLON;
  9889. (function (BABYLON) {
  9890. var ShadowGenerator = (function () {
  9891. function ShadowGenerator(mapSize, light) {
  9892. var _this = this;
  9893. // Members
  9894. this._filter = ShadowGenerator.FILTER_NONE;
  9895. this.blurScale = 2;
  9896. this._blurBoxOffset = 0;
  9897. this._bias = 0.00005;
  9898. this._lightDirection = BABYLON.Vector3.Zero();
  9899. this.forceBackFacesOnly = false;
  9900. this._darkness = 0;
  9901. this._transparencyShadow = false;
  9902. this._viewMatrix = BABYLON.Matrix.Zero();
  9903. this._projectionMatrix = BABYLON.Matrix.Zero();
  9904. this._transformMatrix = BABYLON.Matrix.Zero();
  9905. this._worldViewProjection = BABYLON.Matrix.Zero();
  9906. this._currentFaceIndex = 0;
  9907. this._currentFaceIndexCache = 0;
  9908. this._light = light;
  9909. this._scene = light.getScene();
  9910. this._mapSize = mapSize;
  9911. light._shadowGenerator = this;
  9912. // Render target
  9913. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9914. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9915. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9916. this._shadowMap.anisotropicFilteringLevel = 1;
  9917. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9918. this._shadowMap.renderParticles = false;
  9919. this._shadowMap.onBeforeRender = function (faceIndex) {
  9920. _this._currentFaceIndex = faceIndex;
  9921. };
  9922. this._shadowMap.onAfterUnbind = function () {
  9923. if (!_this.useBlurVarianceShadowMap) {
  9924. return;
  9925. }
  9926. if (!_this._shadowMap2) {
  9927. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9928. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9929. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9930. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9931. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9932. _this._downSamplePostprocess.onApply = function (effect) {
  9933. effect.setTexture("textureSampler", _this._shadowMap);
  9934. };
  9935. _this.blurBoxOffset = 1;
  9936. }
  9937. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9938. };
  9939. // Custom render function
  9940. var renderSubMesh = function (subMesh) {
  9941. var mesh = subMesh.getRenderingMesh();
  9942. var scene = _this._scene;
  9943. var engine = scene.getEngine();
  9944. // Culling
  9945. engine.setState(subMesh.getMaterial().backFaceCulling);
  9946. // Managing instances
  9947. var batch = mesh._getInstancesRenderList(subMesh._id);
  9948. if (batch.mustReturn) {
  9949. return;
  9950. }
  9951. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9952. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9953. engine.enableEffect(_this._effect);
  9954. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9955. var material = subMesh.getMaterial();
  9956. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9957. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9958. if (_this.getLight().needCube()) {
  9959. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9960. }
  9961. // Alpha test
  9962. if (material && material.needAlphaTesting()) {
  9963. var alphaTexture = material.getAlphaTestTexture();
  9964. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9965. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9966. }
  9967. // Bones
  9968. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9969. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9970. }
  9971. if (_this.forceBackFacesOnly) {
  9972. engine.setState(true, 0, false, true);
  9973. }
  9974. // Draw
  9975. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9976. if (_this.forceBackFacesOnly) {
  9977. engine.setState(true, 0, false, false);
  9978. }
  9979. }
  9980. else {
  9981. // Need to reset refresh rate of the shadowMap
  9982. _this._shadowMap.resetRefreshCounter();
  9983. }
  9984. };
  9985. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9986. var index;
  9987. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9988. renderSubMesh(opaqueSubMeshes.data[index]);
  9989. }
  9990. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9991. renderSubMesh(alphaTestSubMeshes.data[index]);
  9992. }
  9993. if (_this._transparencyShadow) {
  9994. for (index = 0; index < transparentSubMeshes.length; index++) {
  9995. renderSubMesh(transparentSubMeshes.data[index]);
  9996. }
  9997. }
  9998. };
  9999. this._shadowMap.onClear = function (engine) {
  10000. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10001. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10002. }
  10003. else {
  10004. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10005. }
  10006. };
  10007. }
  10008. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10009. // Static
  10010. get: function () {
  10011. return ShadowGenerator._FILTER_NONE;
  10012. },
  10013. enumerable: true,
  10014. configurable: true
  10015. });
  10016. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10017. get: function () {
  10018. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10024. get: function () {
  10025. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10031. get: function () {
  10032. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10033. },
  10034. enumerable: true,
  10035. configurable: true
  10036. });
  10037. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10038. get: function () {
  10039. return this._bias;
  10040. },
  10041. set: function (bias) {
  10042. this._bias = bias;
  10043. },
  10044. enumerable: true,
  10045. configurable: true
  10046. });
  10047. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10048. get: function () {
  10049. return this._blurBoxOffset;
  10050. },
  10051. set: function (value) {
  10052. var _this = this;
  10053. if (this._blurBoxOffset === value) {
  10054. return;
  10055. }
  10056. this._blurBoxOffset = value;
  10057. if (this._boxBlurPostprocess) {
  10058. this._boxBlurPostprocess.dispose();
  10059. }
  10060. 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);
  10061. this._boxBlurPostprocess.onApply = function (effect) {
  10062. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10063. };
  10064. },
  10065. enumerable: true,
  10066. configurable: true
  10067. });
  10068. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10069. get: function () {
  10070. return this._filter;
  10071. },
  10072. set: function (value) {
  10073. if (this._filter === value) {
  10074. return;
  10075. }
  10076. this._filter = value;
  10077. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10078. this._shadowMap.anisotropicFilteringLevel = 16;
  10079. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10080. }
  10081. else {
  10082. this._shadowMap.anisotropicFilteringLevel = 1;
  10083. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10084. }
  10085. },
  10086. enumerable: true,
  10087. configurable: true
  10088. });
  10089. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10090. get: function () {
  10091. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10092. },
  10093. set: function (value) {
  10094. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10095. },
  10096. enumerable: true,
  10097. configurable: true
  10098. });
  10099. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10100. get: function () {
  10101. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10102. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10103. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10104. },
  10105. set: function (value) {
  10106. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10107. },
  10108. enumerable: true,
  10109. configurable: true
  10110. });
  10111. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10112. get: function () {
  10113. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10114. },
  10115. set: function (value) {
  10116. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10117. },
  10118. enumerable: true,
  10119. configurable: true
  10120. });
  10121. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10122. var defines = [];
  10123. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10124. defines.push("#define VSM");
  10125. }
  10126. if (this.getLight().needCube()) {
  10127. defines.push("#define CUBEMAP");
  10128. }
  10129. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10130. var mesh = subMesh.getMesh();
  10131. var material = subMesh.getMaterial();
  10132. // Alpha test
  10133. if (material && material.needAlphaTesting()) {
  10134. defines.push("#define ALPHATEST");
  10135. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10136. attribs.push(BABYLON.VertexBuffer.UVKind);
  10137. defines.push("#define UV1");
  10138. }
  10139. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10140. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10141. defines.push("#define UV2");
  10142. }
  10143. }
  10144. // Bones
  10145. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10146. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10147. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10148. if (mesh.numBoneInfluencers > 4) {
  10149. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10150. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10151. }
  10152. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10153. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10154. }
  10155. else {
  10156. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10157. }
  10158. // Instances
  10159. if (useInstances) {
  10160. defines.push("#define INSTANCES");
  10161. attribs.push("world0");
  10162. attribs.push("world1");
  10163. attribs.push("world2");
  10164. attribs.push("world3");
  10165. }
  10166. // Get correct effect
  10167. var join = defines.join("\n");
  10168. if (this._cachedDefines !== join) {
  10169. this._cachedDefines = join;
  10170. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10171. }
  10172. return this._effect.isReady();
  10173. };
  10174. ShadowGenerator.prototype.getShadowMap = function () {
  10175. return this._shadowMap;
  10176. };
  10177. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10178. if (this._shadowMap2) {
  10179. return this._shadowMap2;
  10180. }
  10181. return this._shadowMap;
  10182. };
  10183. ShadowGenerator.prototype.getLight = function () {
  10184. return this._light;
  10185. };
  10186. // Methods
  10187. ShadowGenerator.prototype.getTransformMatrix = function () {
  10188. var scene = this._scene;
  10189. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10190. return this._transformMatrix;
  10191. }
  10192. this._currentRenderID = scene.getRenderId();
  10193. this._currentFaceIndexCache = this._currentFaceIndex;
  10194. var lightPosition = this._light.position;
  10195. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10196. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10197. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10198. }
  10199. if (this._light.computeTransformedPosition()) {
  10200. lightPosition = this._light.transformedPosition;
  10201. }
  10202. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10203. this._cachedPosition = lightPosition.clone();
  10204. this._cachedDirection = this._lightDirection.clone();
  10205. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10206. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10207. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10208. }
  10209. return this._transformMatrix;
  10210. };
  10211. ShadowGenerator.prototype.getDarkness = function () {
  10212. return this._darkness;
  10213. };
  10214. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10215. if (darkness >= 1.0)
  10216. this._darkness = 1.0;
  10217. else if (darkness <= 0.0)
  10218. this._darkness = 0.0;
  10219. else
  10220. this._darkness = darkness;
  10221. };
  10222. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10223. this._transparencyShadow = hasShadow;
  10224. };
  10225. ShadowGenerator.prototype._packHalf = function (depth) {
  10226. var scale = depth * 255.0;
  10227. var fract = scale - Math.floor(scale);
  10228. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10229. };
  10230. ShadowGenerator.prototype.dispose = function () {
  10231. this._shadowMap.dispose();
  10232. if (this._shadowMap2) {
  10233. this._shadowMap2.dispose();
  10234. }
  10235. if (this._downSamplePostprocess) {
  10236. this._downSamplePostprocess.dispose();
  10237. }
  10238. if (this._boxBlurPostprocess) {
  10239. this._boxBlurPostprocess.dispose();
  10240. }
  10241. };
  10242. ShadowGenerator.prototype.serialize = function () {
  10243. var serializationObject = {};
  10244. serializationObject.lightId = this._light.id;
  10245. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10246. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10247. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10248. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10249. serializationObject.renderList = [];
  10250. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10251. var mesh = this.getShadowMap().renderList[meshIndex];
  10252. serializationObject.renderList.push(mesh.id);
  10253. }
  10254. return serializationObject;
  10255. };
  10256. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10257. //casting to point light, as light is missing the position attr and typescript complains.
  10258. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10259. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10260. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10261. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  10262. shadowGenerator.getShadowMap().renderList.push(mesh);
  10263. }
  10264. if (parsedShadowGenerator.usePoissonSampling) {
  10265. shadowGenerator.usePoissonSampling = true;
  10266. }
  10267. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10268. shadowGenerator.useVarianceShadowMap = true;
  10269. }
  10270. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10271. shadowGenerator.useBlurVarianceShadowMap = true;
  10272. if (parsedShadowGenerator.blurScale) {
  10273. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10274. }
  10275. if (parsedShadowGenerator.blurBoxOffset) {
  10276. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10277. }
  10278. }
  10279. if (parsedShadowGenerator.bias !== undefined) {
  10280. shadowGenerator.bias = parsedShadowGenerator.bias;
  10281. }
  10282. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10283. return shadowGenerator;
  10284. };
  10285. ShadowGenerator._FILTER_NONE = 0;
  10286. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10287. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10288. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10289. return ShadowGenerator;
  10290. })();
  10291. BABYLON.ShadowGenerator = ShadowGenerator;
  10292. })(BABYLON || (BABYLON = {}));
  10293. var BABYLON;
  10294. (function (BABYLON) {
  10295. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10296. if (boxMin.x > sphereCenter.x + sphereRadius)
  10297. return false;
  10298. if (sphereCenter.x - sphereRadius > boxMax.x)
  10299. return false;
  10300. if (boxMin.y > sphereCenter.y + sphereRadius)
  10301. return false;
  10302. if (sphereCenter.y - sphereRadius > boxMax.y)
  10303. return false;
  10304. if (boxMin.z > sphereCenter.z + sphereRadius)
  10305. return false;
  10306. if (sphereCenter.z - sphereRadius > boxMax.z)
  10307. return false;
  10308. return true;
  10309. };
  10310. var getLowestRoot = function (a, b, c, maxR) {
  10311. var determinant = b * b - 4.0 * a * c;
  10312. var result = { root: 0, found: false };
  10313. if (determinant < 0)
  10314. return result;
  10315. var sqrtD = Math.sqrt(determinant);
  10316. var r1 = (-b - sqrtD) / (2.0 * a);
  10317. var r2 = (-b + sqrtD) / (2.0 * a);
  10318. if (r1 > r2) {
  10319. var temp = r2;
  10320. r2 = r1;
  10321. r1 = temp;
  10322. }
  10323. if (r1 > 0 && r1 < maxR) {
  10324. result.root = r1;
  10325. result.found = true;
  10326. return result;
  10327. }
  10328. if (r2 > 0 && r2 < maxR) {
  10329. result.root = r2;
  10330. result.found = true;
  10331. return result;
  10332. }
  10333. return result;
  10334. };
  10335. var Collider = (function () {
  10336. function Collider() {
  10337. this.radius = new BABYLON.Vector3(1, 1, 1);
  10338. this.retry = 0;
  10339. this.basePointWorld = BABYLON.Vector3.Zero();
  10340. this.velocityWorld = BABYLON.Vector3.Zero();
  10341. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10342. this._collisionPoint = BABYLON.Vector3.Zero();
  10343. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10344. this._tempVector = BABYLON.Vector3.Zero();
  10345. this._tempVector2 = BABYLON.Vector3.Zero();
  10346. this._tempVector3 = BABYLON.Vector3.Zero();
  10347. this._tempVector4 = BABYLON.Vector3.Zero();
  10348. this._edge = BABYLON.Vector3.Zero();
  10349. this._baseToVertex = BABYLON.Vector3.Zero();
  10350. this._destinationPoint = BABYLON.Vector3.Zero();
  10351. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10352. this._displacementVector = BABYLON.Vector3.Zero();
  10353. }
  10354. // Methods
  10355. Collider.prototype._initialize = function (source, dir, e) {
  10356. this.velocity = dir;
  10357. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10358. this.basePoint = source;
  10359. source.multiplyToRef(this.radius, this.basePointWorld);
  10360. dir.multiplyToRef(this.radius, this.velocityWorld);
  10361. this.velocityWorldLength = this.velocityWorld.length();
  10362. this.epsilon = e;
  10363. this.collisionFound = false;
  10364. };
  10365. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10366. pa.subtractToRef(point, this._tempVector);
  10367. pb.subtractToRef(point, this._tempVector2);
  10368. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10369. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10370. if (d < 0)
  10371. return false;
  10372. pc.subtractToRef(point, this._tempVector3);
  10373. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10374. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10375. if (d < 0)
  10376. return false;
  10377. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10378. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10379. return d >= 0;
  10380. };
  10381. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10382. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10383. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10384. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10385. return false;
  10386. }
  10387. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10388. return false;
  10389. return true;
  10390. };
  10391. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10392. var t0;
  10393. var embeddedInPlane = false;
  10394. //defensive programming, actually not needed.
  10395. if (!trianglePlaneArray) {
  10396. trianglePlaneArray = [];
  10397. }
  10398. if (!trianglePlaneArray[faceIndex]) {
  10399. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10400. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10401. }
  10402. var trianglePlane = trianglePlaneArray[faceIndex];
  10403. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10404. return;
  10405. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10406. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10407. if (normalDotVelocity == 0) {
  10408. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10409. return;
  10410. embeddedInPlane = true;
  10411. t0 = 0;
  10412. }
  10413. else {
  10414. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10415. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10416. if (t0 > t1) {
  10417. var temp = t1;
  10418. t1 = t0;
  10419. t0 = temp;
  10420. }
  10421. if (t0 > 1.0 || t1 < 0.0)
  10422. return;
  10423. if (t0 < 0)
  10424. t0 = 0;
  10425. if (t0 > 1.0)
  10426. t0 = 1.0;
  10427. }
  10428. this._collisionPoint.copyFromFloats(0, 0, 0);
  10429. var found = false;
  10430. var t = 1.0;
  10431. if (!embeddedInPlane) {
  10432. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10433. this.velocity.scaleToRef(t0, this._tempVector);
  10434. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10435. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10436. found = true;
  10437. t = t0;
  10438. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10439. }
  10440. }
  10441. if (!found) {
  10442. var velocitySquaredLength = this.velocity.lengthSquared();
  10443. var a = velocitySquaredLength;
  10444. this.basePoint.subtractToRef(p1, this._tempVector);
  10445. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10446. var c = this._tempVector.lengthSquared() - 1.0;
  10447. var lowestRoot = getLowestRoot(a, b, c, t);
  10448. if (lowestRoot.found) {
  10449. t = lowestRoot.root;
  10450. found = true;
  10451. this._collisionPoint.copyFrom(p1);
  10452. }
  10453. this.basePoint.subtractToRef(p2, this._tempVector);
  10454. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10455. c = this._tempVector.lengthSquared() - 1.0;
  10456. lowestRoot = getLowestRoot(a, b, c, t);
  10457. if (lowestRoot.found) {
  10458. t = lowestRoot.root;
  10459. found = true;
  10460. this._collisionPoint.copyFrom(p2);
  10461. }
  10462. this.basePoint.subtractToRef(p3, this._tempVector);
  10463. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10464. c = this._tempVector.lengthSquared() - 1.0;
  10465. lowestRoot = getLowestRoot(a, b, c, t);
  10466. if (lowestRoot.found) {
  10467. t = lowestRoot.root;
  10468. found = true;
  10469. this._collisionPoint.copyFrom(p3);
  10470. }
  10471. p2.subtractToRef(p1, this._edge);
  10472. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10473. var edgeSquaredLength = this._edge.lengthSquared();
  10474. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10475. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10476. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10477. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10478. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10479. lowestRoot = getLowestRoot(a, b, c, t);
  10480. if (lowestRoot.found) {
  10481. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10482. if (f >= 0.0 && f <= 1.0) {
  10483. t = lowestRoot.root;
  10484. found = true;
  10485. this._edge.scaleInPlace(f);
  10486. p1.addToRef(this._edge, this._collisionPoint);
  10487. }
  10488. }
  10489. p3.subtractToRef(p2, this._edge);
  10490. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10491. edgeSquaredLength = this._edge.lengthSquared();
  10492. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10493. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10494. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10495. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10496. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10497. lowestRoot = getLowestRoot(a, b, c, t);
  10498. if (lowestRoot.found) {
  10499. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10500. if (f >= 0.0 && f <= 1.0) {
  10501. t = lowestRoot.root;
  10502. found = true;
  10503. this._edge.scaleInPlace(f);
  10504. p2.addToRef(this._edge, this._collisionPoint);
  10505. }
  10506. }
  10507. p1.subtractToRef(p3, this._edge);
  10508. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10509. edgeSquaredLength = this._edge.lengthSquared();
  10510. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10511. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10512. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10513. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10514. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10515. lowestRoot = getLowestRoot(a, b, c, t);
  10516. if (lowestRoot.found) {
  10517. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10518. if (f >= 0.0 && f <= 1.0) {
  10519. t = lowestRoot.root;
  10520. found = true;
  10521. this._edge.scaleInPlace(f);
  10522. p3.addToRef(this._edge, this._collisionPoint);
  10523. }
  10524. }
  10525. }
  10526. if (found) {
  10527. var distToCollision = t * this.velocity.length();
  10528. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10529. if (!this.intersectionPoint) {
  10530. this.intersectionPoint = this._collisionPoint.clone();
  10531. }
  10532. else {
  10533. this.intersectionPoint.copyFrom(this._collisionPoint);
  10534. }
  10535. this.nearestDistance = distToCollision;
  10536. this.collisionFound = true;
  10537. }
  10538. }
  10539. };
  10540. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10541. for (var i = indexStart; i < indexEnd; i += 3) {
  10542. var p1 = pts[indices[i] - decal];
  10543. var p2 = pts[indices[i + 1] - decal];
  10544. var p3 = pts[indices[i + 2] - decal];
  10545. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10546. }
  10547. };
  10548. Collider.prototype._getResponse = function (pos, vel) {
  10549. pos.addToRef(vel, this._destinationPoint);
  10550. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10551. this.basePoint.addToRef(vel, pos);
  10552. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10553. this._slidePlaneNormal.normalize();
  10554. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10555. pos.addInPlace(this._displacementVector);
  10556. this.intersectionPoint.addInPlace(this._displacementVector);
  10557. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10558. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10559. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10560. };
  10561. return Collider;
  10562. })();
  10563. BABYLON.Collider = Collider;
  10564. })(BABYLON || (BABYLON = {}));
  10565. var BABYLON;
  10566. (function (BABYLON) {
  10567. //WebWorker code will be inserted to this variable.
  10568. BABYLON.CollisionWorker = "";
  10569. (function (WorkerTaskType) {
  10570. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10571. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10572. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10573. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10574. var WorkerTaskType = BABYLON.WorkerTaskType;
  10575. (function (WorkerReplyType) {
  10576. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10577. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10578. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10579. var WorkerReplyType = BABYLON.WorkerReplyType;
  10580. var CollisionCoordinatorWorker = (function () {
  10581. function CollisionCoordinatorWorker() {
  10582. var _this = this;
  10583. this._scaledPosition = BABYLON.Vector3.Zero();
  10584. this._scaledVelocity = BABYLON.Vector3.Zero();
  10585. this.onMeshUpdated = function (mesh) {
  10586. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10587. };
  10588. this.onGeometryUpdated = function (geometry) {
  10589. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10590. };
  10591. this._afterRender = function () {
  10592. if (!_this._init)
  10593. return;
  10594. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10595. return;
  10596. }
  10597. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10598. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10599. if (_this._runningUpdated > 4) {
  10600. return;
  10601. }
  10602. ++_this._runningUpdated;
  10603. var payload = {
  10604. updatedMeshes: _this._addUpdateMeshesList,
  10605. updatedGeometries: _this._addUpdateGeometriesList,
  10606. removedGeometries: _this._toRemoveGeometryArray,
  10607. removedMeshes: _this._toRemoveMeshesArray
  10608. };
  10609. var message = {
  10610. payload: payload,
  10611. taskType: WorkerTaskType.UPDATE
  10612. };
  10613. var serializable = [];
  10614. for (var id in payload.updatedGeometries) {
  10615. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10616. //prepare transferables
  10617. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10618. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10619. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10620. }
  10621. }
  10622. _this._worker.postMessage(message, serializable);
  10623. _this._addUpdateMeshesList = {};
  10624. _this._addUpdateGeometriesList = {};
  10625. _this._toRemoveGeometryArray = [];
  10626. _this._toRemoveMeshesArray = [];
  10627. };
  10628. this._onMessageFromWorker = function (e) {
  10629. var returnData = e.data;
  10630. if (returnData.error != WorkerReplyType.SUCCESS) {
  10631. //TODO what errors can be returned from the worker?
  10632. BABYLON.Tools.Warn("error returned from worker!");
  10633. return;
  10634. }
  10635. switch (returnData.taskType) {
  10636. case WorkerTaskType.INIT:
  10637. _this._init = true;
  10638. //Update the worked with ALL of the scene's current state
  10639. _this._scene.meshes.forEach(function (mesh) {
  10640. _this.onMeshAdded(mesh);
  10641. });
  10642. _this._scene.getGeometries().forEach(function (geometry) {
  10643. _this.onGeometryAdded(geometry);
  10644. });
  10645. break;
  10646. case WorkerTaskType.UPDATE:
  10647. _this._runningUpdated--;
  10648. break;
  10649. case WorkerTaskType.COLLIDE:
  10650. _this._runningCollisionTask = false;
  10651. var returnPayload = returnData.payload;
  10652. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10653. return;
  10654. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10655. //cleanup
  10656. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10657. break;
  10658. }
  10659. };
  10660. this._collisionsCallbackArray = [];
  10661. this._init = false;
  10662. this._runningUpdated = 0;
  10663. this._runningCollisionTask = false;
  10664. this._addUpdateMeshesList = {};
  10665. this._addUpdateGeometriesList = {};
  10666. this._toRemoveGeometryArray = [];
  10667. this._toRemoveMeshesArray = [];
  10668. }
  10669. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10670. if (!this._init)
  10671. return;
  10672. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10673. return;
  10674. position.divideToRef(collider.radius, this._scaledPosition);
  10675. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10676. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10677. var payload = {
  10678. collider: {
  10679. position: this._scaledPosition.asArray(),
  10680. velocity: this._scaledVelocity.asArray(),
  10681. radius: collider.radius.asArray()
  10682. },
  10683. collisionId: collisionIndex,
  10684. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10685. maximumRetry: maximumRetry
  10686. };
  10687. var message = {
  10688. payload: payload,
  10689. taskType: WorkerTaskType.COLLIDE
  10690. };
  10691. this._worker.postMessage(message);
  10692. };
  10693. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10694. this._scene = scene;
  10695. this._scene.registerAfterRender(this._afterRender);
  10696. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10697. this._worker = new Worker(workerUrl);
  10698. this._worker.onmessage = this._onMessageFromWorker;
  10699. var message = {
  10700. payload: {},
  10701. taskType: WorkerTaskType.INIT
  10702. };
  10703. this._worker.postMessage(message);
  10704. };
  10705. CollisionCoordinatorWorker.prototype.destroy = function () {
  10706. this._scene.unregisterAfterRender(this._afterRender);
  10707. this._worker.terminate();
  10708. };
  10709. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10710. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10711. this.onMeshUpdated(mesh);
  10712. };
  10713. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10714. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10715. };
  10716. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10717. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10718. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10719. this.onGeometryUpdated(geometry);
  10720. };
  10721. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10722. this._toRemoveGeometryArray.push(geometry.id);
  10723. };
  10724. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10725. var submeshes = [];
  10726. if (mesh.subMeshes) {
  10727. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10728. return {
  10729. position: idx,
  10730. verticesStart: sm.verticesStart,
  10731. verticesCount: sm.verticesCount,
  10732. indexStart: sm.indexStart,
  10733. indexCount: sm.indexCount,
  10734. hasMaterial: !!sm.getMaterial(),
  10735. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10736. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10737. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10738. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10739. };
  10740. });
  10741. }
  10742. var geometryId = null;
  10743. if (mesh instanceof BABYLON.Mesh) {
  10744. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10745. }
  10746. else if (mesh instanceof BABYLON.InstancedMesh) {
  10747. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10748. }
  10749. return {
  10750. uniqueId: mesh.uniqueId,
  10751. id: mesh.id,
  10752. name: mesh.name,
  10753. geometryId: geometryId,
  10754. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10755. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10756. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10757. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10758. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10759. subMeshes: submeshes,
  10760. checkCollisions: mesh.checkCollisions
  10761. };
  10762. };
  10763. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10764. return {
  10765. id: geometry.id,
  10766. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10767. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10768. indices: new Int32Array(geometry.getIndices() || []),
  10769. };
  10770. };
  10771. return CollisionCoordinatorWorker;
  10772. })();
  10773. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10774. var CollisionCoordinatorLegacy = (function () {
  10775. function CollisionCoordinatorLegacy() {
  10776. this._scaledPosition = BABYLON.Vector3.Zero();
  10777. this._scaledVelocity = BABYLON.Vector3.Zero();
  10778. this._finalPosition = BABYLON.Vector3.Zero();
  10779. }
  10780. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10781. position.divideToRef(collider.radius, this._scaledPosition);
  10782. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10783. collider.collidedMesh = null;
  10784. collider.retry = 0;
  10785. collider.initialVelocity = this._scaledVelocity;
  10786. collider.initialPosition = this._scaledPosition;
  10787. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10788. this._finalPosition.multiplyInPlace(collider.radius);
  10789. //run the callback
  10790. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10791. };
  10792. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10793. this._scene = scene;
  10794. };
  10795. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10796. //Legacy need no destruction method.
  10797. };
  10798. //No update in legacy mode
  10799. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10800. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10801. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10802. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10803. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10804. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10805. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10806. if (excludedMesh === void 0) { excludedMesh = null; }
  10807. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10808. if (collider.retry >= maximumRetry) {
  10809. finalPosition.copyFrom(position);
  10810. return;
  10811. }
  10812. collider._initialize(position, velocity, closeDistance);
  10813. // Check all meshes
  10814. for (var index = 0; index < this._scene.meshes.length; index++) {
  10815. var mesh = this._scene.meshes[index];
  10816. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10817. mesh._checkCollision(collider);
  10818. }
  10819. }
  10820. if (!collider.collisionFound) {
  10821. position.addToRef(velocity, finalPosition);
  10822. return;
  10823. }
  10824. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10825. collider._getResponse(position, velocity);
  10826. }
  10827. if (velocity.length() <= closeDistance) {
  10828. finalPosition.copyFrom(position);
  10829. return;
  10830. }
  10831. collider.retry++;
  10832. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10833. };
  10834. return CollisionCoordinatorLegacy;
  10835. })();
  10836. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10837. })(BABYLON || (BABYLON = {}));
  10838. var BABYLON;
  10839. (function (BABYLON) {
  10840. var Camera = (function (_super) {
  10841. __extends(Camera, _super);
  10842. function Camera(name, position, scene) {
  10843. _super.call(this, name, scene);
  10844. this.upVector = BABYLON.Vector3.Up();
  10845. this.orthoLeft = null;
  10846. this.orthoRight = null;
  10847. this.orthoBottom = null;
  10848. this.orthoTop = null;
  10849. this.fov = 0.8;
  10850. this.minZ = 1.0;
  10851. this.maxZ = 10000.0;
  10852. this.inertia = 0.9;
  10853. this.mode = Camera.PERSPECTIVE_CAMERA;
  10854. this.isIntermediate = false;
  10855. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10856. this.layerMask = 0x0FFFFFFF;
  10857. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10858. // Camera rig members
  10859. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10860. this._rigCameras = new Array();
  10861. // Cache
  10862. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10863. this._projectionMatrix = new BABYLON.Matrix();
  10864. this._postProcesses = new Array();
  10865. this._postProcessesTakenIndices = [];
  10866. this._activeMeshes = new BABYLON.SmartArray(256);
  10867. this._globalPosition = BABYLON.Vector3.Zero();
  10868. scene.addCamera(this);
  10869. if (!scene.activeCamera) {
  10870. scene.activeCamera = this;
  10871. }
  10872. this.position = position;
  10873. }
  10874. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10875. get: function () {
  10876. return Camera._PERSPECTIVE_CAMERA;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10882. get: function () {
  10883. return Camera._ORTHOGRAPHIC_CAMERA;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10889. get: function () {
  10890. return Camera._FOVMODE_VERTICAL_FIXED;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10896. get: function () {
  10897. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10903. get: function () {
  10904. return Camera._RIG_MODE_NONE;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10910. get: function () {
  10911. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10917. get: function () {
  10918. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10924. get: function () {
  10925. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10931. get: function () {
  10932. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10938. get: function () {
  10939. return Camera._RIG_MODE_VR;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. /**
  10945. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10946. */
  10947. Camera.prototype.toString = function (fullDetails) {
  10948. var ret = "Name: " + this.name;
  10949. ret += ", type: " + this.getTypeName();
  10950. if (this.animations) {
  10951. for (var i = 0; i < this.animations.length; i++) {
  10952. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10953. }
  10954. }
  10955. if (fullDetails) {
  10956. }
  10957. return ret;
  10958. };
  10959. Object.defineProperty(Camera.prototype, "globalPosition", {
  10960. get: function () {
  10961. return this._globalPosition;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Camera.prototype.getActiveMeshes = function () {
  10967. return this._activeMeshes;
  10968. };
  10969. Camera.prototype.isActiveMesh = function (mesh) {
  10970. return (this._activeMeshes.indexOf(mesh) !== -1);
  10971. };
  10972. //Cache
  10973. Camera.prototype._initCache = function () {
  10974. _super.prototype._initCache.call(this);
  10975. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10976. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10977. this._cache.mode = undefined;
  10978. this._cache.minZ = undefined;
  10979. this._cache.maxZ = undefined;
  10980. this._cache.fov = undefined;
  10981. this._cache.aspectRatio = undefined;
  10982. this._cache.orthoLeft = undefined;
  10983. this._cache.orthoRight = undefined;
  10984. this._cache.orthoBottom = undefined;
  10985. this._cache.orthoTop = undefined;
  10986. this._cache.renderWidth = undefined;
  10987. this._cache.renderHeight = undefined;
  10988. };
  10989. Camera.prototype._updateCache = function (ignoreParentClass) {
  10990. if (!ignoreParentClass) {
  10991. _super.prototype._updateCache.call(this);
  10992. }
  10993. var engine = this.getEngine();
  10994. this._cache.position.copyFrom(this.position);
  10995. this._cache.upVector.copyFrom(this.upVector);
  10996. this._cache.mode = this.mode;
  10997. this._cache.minZ = this.minZ;
  10998. this._cache.maxZ = this.maxZ;
  10999. this._cache.fov = this.fov;
  11000. this._cache.aspectRatio = engine.getAspectRatio(this);
  11001. this._cache.orthoLeft = this.orthoLeft;
  11002. this._cache.orthoRight = this.orthoRight;
  11003. this._cache.orthoBottom = this.orthoBottom;
  11004. this._cache.orthoTop = this.orthoTop;
  11005. this._cache.renderWidth = engine.getRenderWidth();
  11006. this._cache.renderHeight = engine.getRenderHeight();
  11007. };
  11008. Camera.prototype._updateFromScene = function () {
  11009. this.updateCache();
  11010. this._update();
  11011. };
  11012. // Synchronized
  11013. Camera.prototype._isSynchronized = function () {
  11014. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11015. };
  11016. Camera.prototype._isSynchronizedViewMatrix = function () {
  11017. if (!_super.prototype._isSynchronized.call(this))
  11018. return false;
  11019. return this._cache.position.equals(this.position)
  11020. && this._cache.upVector.equals(this.upVector)
  11021. && this.isSynchronizedWithParent();
  11022. };
  11023. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11024. var check = this._cache.mode === this.mode
  11025. && this._cache.minZ === this.minZ
  11026. && this._cache.maxZ === this.maxZ;
  11027. if (!check) {
  11028. return false;
  11029. }
  11030. var engine = this.getEngine();
  11031. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11032. check = this._cache.fov === this.fov
  11033. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11034. }
  11035. else {
  11036. check = this._cache.orthoLeft === this.orthoLeft
  11037. && this._cache.orthoRight === this.orthoRight
  11038. && this._cache.orthoBottom === this.orthoBottom
  11039. && this._cache.orthoTop === this.orthoTop
  11040. && this._cache.renderWidth === engine.getRenderWidth()
  11041. && this._cache.renderHeight === engine.getRenderHeight();
  11042. }
  11043. return check;
  11044. };
  11045. // Controls
  11046. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11047. };
  11048. Camera.prototype.detachControl = function (element) {
  11049. };
  11050. Camera.prototype._update = function () {
  11051. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11052. this._updateRigCameras();
  11053. }
  11054. this._checkInputs();
  11055. };
  11056. Camera.prototype._checkInputs = function () {
  11057. };
  11058. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11059. if (insertAt === void 0) { insertAt = null; }
  11060. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11061. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11062. return 0;
  11063. }
  11064. if (insertAt == null || insertAt < 0) {
  11065. this._postProcesses.push(postProcess);
  11066. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11067. return this._postProcesses.length - 1;
  11068. }
  11069. var add = 0;
  11070. var i;
  11071. var start;
  11072. if (this._postProcesses[insertAt]) {
  11073. start = this._postProcesses.length - 1;
  11074. for (i = start; i >= insertAt + 1; --i) {
  11075. this._postProcesses[i + 1] = this._postProcesses[i];
  11076. }
  11077. add = 1;
  11078. }
  11079. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11080. if (this._postProcessesTakenIndices[i] < insertAt) {
  11081. continue;
  11082. }
  11083. start = this._postProcessesTakenIndices.length - 1;
  11084. for (var j = start; j >= i; --j) {
  11085. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11086. }
  11087. this._postProcessesTakenIndices[i] = insertAt;
  11088. break;
  11089. }
  11090. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11091. this._postProcessesTakenIndices.push(insertAt);
  11092. }
  11093. var result = insertAt + add;
  11094. this._postProcesses[result] = postProcess;
  11095. return result;
  11096. };
  11097. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11098. if (atIndices === void 0) { atIndices = null; }
  11099. var result = [];
  11100. var i;
  11101. var index;
  11102. if (!atIndices) {
  11103. var length = this._postProcesses.length;
  11104. for (i = 0; i < length; i++) {
  11105. if (this._postProcesses[i] !== postProcess) {
  11106. continue;
  11107. }
  11108. delete this._postProcesses[i];
  11109. index = this._postProcessesTakenIndices.indexOf(i);
  11110. this._postProcessesTakenIndices.splice(index, 1);
  11111. }
  11112. }
  11113. else {
  11114. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11115. for (i = 0; i < atIndices.length; i++) {
  11116. var foundPostProcess = this._postProcesses[atIndices[i]];
  11117. if (foundPostProcess !== postProcess) {
  11118. result.push(i);
  11119. continue;
  11120. }
  11121. delete this._postProcesses[atIndices[i]];
  11122. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11123. this._postProcessesTakenIndices.splice(index, 1);
  11124. }
  11125. }
  11126. return result;
  11127. };
  11128. Camera.prototype.getWorldMatrix = function () {
  11129. if (!this._worldMatrix) {
  11130. this._worldMatrix = BABYLON.Matrix.Identity();
  11131. }
  11132. var viewMatrix = this.getViewMatrix();
  11133. viewMatrix.invertToRef(this._worldMatrix);
  11134. return this._worldMatrix;
  11135. };
  11136. Camera.prototype._getViewMatrix = function () {
  11137. return BABYLON.Matrix.Identity();
  11138. };
  11139. Camera.prototype.getViewMatrix = function (force) {
  11140. this._computedViewMatrix = this._computeViewMatrix(force);
  11141. if (!force && this._isSynchronizedViewMatrix()) {
  11142. return this._computedViewMatrix;
  11143. }
  11144. if (!this.parent || !this.parent.getWorldMatrix) {
  11145. this._globalPosition.copyFrom(this.position);
  11146. }
  11147. else {
  11148. if (!this._worldMatrix) {
  11149. this._worldMatrix = BABYLON.Matrix.Identity();
  11150. }
  11151. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11152. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11153. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11154. this._computedViewMatrix.invert();
  11155. this._markSyncedWithParent();
  11156. }
  11157. this._currentRenderId = this.getScene().getRenderId();
  11158. return this._computedViewMatrix;
  11159. };
  11160. Camera.prototype._computeViewMatrix = function (force) {
  11161. if (!force && this._isSynchronizedViewMatrix()) {
  11162. return this._computedViewMatrix;
  11163. }
  11164. this._computedViewMatrix = this._getViewMatrix();
  11165. this._currentRenderId = this.getScene().getRenderId();
  11166. return this._computedViewMatrix;
  11167. };
  11168. Camera.prototype.getProjectionMatrix = function (force) {
  11169. if (!force && this._isSynchronizedProjectionMatrix()) {
  11170. return this._projectionMatrix;
  11171. }
  11172. var engine = this.getEngine();
  11173. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11174. if (this.minZ <= 0) {
  11175. this.minZ = 0.1;
  11176. }
  11177. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11178. return this._projectionMatrix;
  11179. }
  11180. var halfWidth = engine.getRenderWidth() / 2.0;
  11181. var halfHeight = engine.getRenderHeight() / 2.0;
  11182. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11183. return this._projectionMatrix;
  11184. };
  11185. Camera.prototype.dispose = function () {
  11186. // Animations
  11187. this.getScene().stopAnimation(this);
  11188. // Remove from scene
  11189. this.getScene().removeCamera(this);
  11190. while (this._rigCameras.length > 0) {
  11191. this._rigCameras.pop().dispose();
  11192. }
  11193. // Postprocesses
  11194. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11195. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11196. }
  11197. _super.prototype.dispose.call(this);
  11198. };
  11199. // ---- Camera rigs section ----
  11200. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11201. while (this._rigCameras.length > 0) {
  11202. this._rigCameras.pop().dispose();
  11203. }
  11204. this.cameraRigMode = mode;
  11205. this._cameraRigParams = {};
  11206. switch (this.cameraRigMode) {
  11207. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11208. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11209. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11210. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11211. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11212. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11213. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11214. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11215. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11216. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11217. break;
  11218. }
  11219. var postProcesses = new Array();
  11220. switch (this.cameraRigMode) {
  11221. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11222. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11223. this._rigCameras[0].isIntermediate = true;
  11224. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11225. postProcesses[1].onApply = function (effect) {
  11226. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11227. };
  11228. break;
  11229. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11230. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11231. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11232. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11233. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11234. var secondCamIndex = 1 - firstCamIndex;
  11235. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11236. this._rigCameras[firstCamIndex].isIntermediate = true;
  11237. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11238. break;
  11239. case Camera.RIG_MODE_VR:
  11240. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11241. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11242. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11243. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11244. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11245. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11246. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11247. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11248. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11249. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11250. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11251. if (metrics.compensateDistortion) {
  11252. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11253. }
  11254. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11255. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11256. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11257. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11258. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11259. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11260. if (metrics.compensateDistortion) {
  11261. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11262. }
  11263. break;
  11264. }
  11265. this._update();
  11266. };
  11267. Camera.prototype._getVRProjectionMatrix = function () {
  11268. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11269. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11270. return this._projectionMatrix;
  11271. };
  11272. Camera.prototype.setCameraRigParameter = function (name, value) {
  11273. this._cameraRigParams[name] = value;
  11274. //provisionnally:
  11275. if (name === "interaxialDistance") {
  11276. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11277. }
  11278. };
  11279. /**
  11280. * May needs to be overridden by children so sub has required properties to be copied
  11281. */
  11282. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11283. return null;
  11284. };
  11285. /**
  11286. * May needs to be overridden by children
  11287. */
  11288. Camera.prototype._updateRigCameras = function () {
  11289. for (var i = 0; i < this._rigCameras.length; i++) {
  11290. this._rigCameras[i].minZ = this.minZ;
  11291. this._rigCameras[i].maxZ = this.maxZ;
  11292. this._rigCameras[i].fov = this.fov;
  11293. }
  11294. // only update viewport when ANAGLYPH
  11295. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11296. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11297. }
  11298. };
  11299. Camera.prototype._setupInputs = function () {
  11300. };
  11301. Camera.prototype.serialize = function () {
  11302. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11303. // Type
  11304. serializationObject.type = this.getTypeName();
  11305. // Parent
  11306. if (this.parent) {
  11307. serializationObject.parentId = this.parent.id;
  11308. }
  11309. if (this.inputs) {
  11310. this.inputs.serialize(serializationObject);
  11311. }
  11312. // Animations
  11313. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11314. serializationObject.ranges = this.serializeAnimationRanges();
  11315. return serializationObject;
  11316. };
  11317. Camera.prototype.getTypeName = function () {
  11318. return "Camera";
  11319. };
  11320. Camera.prototype.clone = function (name) {
  11321. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11322. };
  11323. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11324. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11325. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11326. switch (type) {
  11327. case "ArcRotateCamera":
  11328. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11329. case "DeviceOrientationCamera":
  11330. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11331. case "FollowCamera":
  11332. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11333. case "ArcFollowCamera":
  11334. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11335. case "GamepadCamera":
  11336. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11337. case "TouchCamera":
  11338. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11339. case "VirtualJoysticksCamera":
  11340. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11341. case "WebVRFreeCamera":
  11342. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11343. case "VRDeviceOrientationFreeCamera":
  11344. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11345. case "AnaglyphArcRotateCamera":
  11346. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11347. case "AnaglyphFreeCamera":
  11348. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11349. case "AnaglyphGamepadCamera":
  11350. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11351. case "AnaglyphUniversalCamera":
  11352. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11353. case "StereoscopicArcRotateCamera":
  11354. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11355. case "StereoscopicFreeCamera":
  11356. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11357. case "StereoscopicGamepadCamera":
  11358. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11359. case "StereoscopicUniversalCamera":
  11360. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11361. case "FreeCamera":
  11362. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11363. default:
  11364. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11365. }
  11366. };
  11367. Camera.Parse = function (parsedCamera, scene) {
  11368. var type = parsedCamera.type;
  11369. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11370. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11371. // Parent
  11372. if (parsedCamera.parentId) {
  11373. camera._waitingParentId = parsedCamera.parentId;
  11374. }
  11375. //If camera has an input manager, let it parse inputs settings
  11376. if (camera.inputs) {
  11377. camera.inputs.parse(parsedCamera);
  11378. camera._setupInputs();
  11379. }
  11380. // Target
  11381. if (parsedCamera.target) {
  11382. if (camera.setTarget) {
  11383. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11384. }
  11385. }
  11386. // Apply 3d rig, when found
  11387. if (parsedCamera.cameraRigMode) {
  11388. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11389. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11390. }
  11391. // Animations
  11392. if (parsedCamera.animations) {
  11393. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11394. var parsedAnimation = parsedCamera.animations[animationIndex];
  11395. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11396. }
  11397. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11398. }
  11399. if (parsedCamera.autoAnimate) {
  11400. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11401. }
  11402. return camera;
  11403. };
  11404. // Statics
  11405. Camera._PERSPECTIVE_CAMERA = 0;
  11406. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11407. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11408. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11409. Camera._RIG_MODE_NONE = 0;
  11410. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11411. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11412. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11413. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11414. Camera._RIG_MODE_VR = 20;
  11415. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11416. __decorate([
  11417. BABYLON.serializeAsVector3()
  11418. ], Camera.prototype, "position", void 0);
  11419. __decorate([
  11420. BABYLON.serializeAsVector3()
  11421. ], Camera.prototype, "upVector", void 0);
  11422. __decorate([
  11423. BABYLON.serialize()
  11424. ], Camera.prototype, "orthoLeft", void 0);
  11425. __decorate([
  11426. BABYLON.serialize()
  11427. ], Camera.prototype, "orthoRight", void 0);
  11428. __decorate([
  11429. BABYLON.serialize()
  11430. ], Camera.prototype, "orthoBottom", void 0);
  11431. __decorate([
  11432. BABYLON.serialize()
  11433. ], Camera.prototype, "orthoTop", void 0);
  11434. __decorate([
  11435. BABYLON.serialize()
  11436. ], Camera.prototype, "fov", void 0);
  11437. __decorate([
  11438. BABYLON.serialize()
  11439. ], Camera.prototype, "minZ", void 0);
  11440. __decorate([
  11441. BABYLON.serialize()
  11442. ], Camera.prototype, "maxZ", void 0);
  11443. __decorate([
  11444. BABYLON.serialize()
  11445. ], Camera.prototype, "inertia", void 0);
  11446. __decorate([
  11447. BABYLON.serialize()
  11448. ], Camera.prototype, "mode", void 0);
  11449. __decorate([
  11450. BABYLON.serialize()
  11451. ], Camera.prototype, "layerMask", void 0);
  11452. __decorate([
  11453. BABYLON.serialize()
  11454. ], Camera.prototype, "fovMode", void 0);
  11455. __decorate([
  11456. BABYLON.serialize()
  11457. ], Camera.prototype, "cameraRigMode", void 0);
  11458. __decorate([
  11459. BABYLON.serialize()
  11460. ], Camera.prototype, "interaxialDistance", void 0);
  11461. __decorate([
  11462. BABYLON.serialize()
  11463. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11464. return Camera;
  11465. })(BABYLON.Node);
  11466. BABYLON.Camera = Camera;
  11467. })(BABYLON || (BABYLON = {}));
  11468. var BABYLON;
  11469. (function (BABYLON) {
  11470. BABYLON.CameraInputTypes = {};
  11471. var CameraInputsManager = (function () {
  11472. function CameraInputsManager(camera) {
  11473. this.attached = {};
  11474. this.camera = camera;
  11475. this.checkInputs = function () { };
  11476. }
  11477. CameraInputsManager.prototype.add = function (input) {
  11478. var type = input.getSimpleName();
  11479. if (this.attached[type]) {
  11480. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11481. return;
  11482. }
  11483. this.attached[type] = input;
  11484. input.camera = this.camera;
  11485. //for checkInputs, we are dynamically creating a function
  11486. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11487. if (input.checkInputs) {
  11488. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11489. }
  11490. if (this.attachedElement) {
  11491. input.attachControl(this.attachedElement);
  11492. }
  11493. };
  11494. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11495. for (var cam in this.attached) {
  11496. var input = this.attached[cam];
  11497. if (input === inputToRemove) {
  11498. input.detachControl(this.attachedElement);
  11499. delete this.attached[cam];
  11500. this.rebuildInputCheck();
  11501. }
  11502. }
  11503. };
  11504. CameraInputsManager.prototype.removeByType = function (inputType) {
  11505. for (var cam in this.attached) {
  11506. var input = this.attached[cam];
  11507. if (input.getTypeName() === inputType) {
  11508. input.detachControl(this.attachedElement);
  11509. delete this.attached[cam];
  11510. this.rebuildInputCheck();
  11511. }
  11512. }
  11513. };
  11514. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11515. var current = this.checkInputs;
  11516. return function () {
  11517. current();
  11518. fn();
  11519. };
  11520. };
  11521. CameraInputsManager.prototype.attachInput = function (input) {
  11522. input.attachControl(this.attachedElement, this.noPreventDefault);
  11523. };
  11524. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11525. if (this.attachedElement) {
  11526. return;
  11527. }
  11528. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11529. this.attachedElement = element;
  11530. this.noPreventDefault = noPreventDefault;
  11531. for (var cam in this.attached) {
  11532. var input = this.attached[cam];
  11533. this.attached[cam].attachControl(element, noPreventDefault);
  11534. }
  11535. };
  11536. CameraInputsManager.prototype.detachElement = function (element) {
  11537. if (this.attachedElement !== element) {
  11538. return;
  11539. }
  11540. for (var cam in this.attached) {
  11541. var input = this.attached[cam];
  11542. this.attached[cam].detachControl(element);
  11543. }
  11544. this.attachedElement = null;
  11545. };
  11546. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11547. this.checkInputs = function () { };
  11548. for (var cam in this.attached) {
  11549. var input = this.attached[cam];
  11550. if (input.checkInputs) {
  11551. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11552. }
  11553. }
  11554. };
  11555. CameraInputsManager.prototype.clear = function () {
  11556. if (this.attachedElement) {
  11557. this.detachElement(this.attachedElement);
  11558. }
  11559. this.attached = {};
  11560. this.attachedElement = null;
  11561. this.checkInputs = function () { };
  11562. };
  11563. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11564. var inputs = {};
  11565. for (var cam in this.attached) {
  11566. var input = this.attached[cam];
  11567. var res = BABYLON.SerializationHelper.Serialize(input);
  11568. inputs[input.getTypeName()] = res;
  11569. }
  11570. serializedCamera.inputsmgr = inputs;
  11571. };
  11572. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11573. var parsedInputs = parsedCamera.inputsmgr;
  11574. if (parsedInputs) {
  11575. this.clear();
  11576. for (var n in parsedInputs) {
  11577. var construct = BABYLON.CameraInputTypes[n];
  11578. if (construct) {
  11579. var parsedinput = parsedInputs[n];
  11580. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11581. this.add(input);
  11582. }
  11583. }
  11584. }
  11585. else {
  11586. //2016-03-08 this part is for managing backward compatibility
  11587. for (var n in this.attached) {
  11588. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11589. if (construct) {
  11590. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11591. this.remove(this.attached[n]);
  11592. this.add(input);
  11593. }
  11594. }
  11595. }
  11596. };
  11597. return CameraInputsManager;
  11598. })();
  11599. BABYLON.CameraInputsManager = CameraInputsManager;
  11600. })(BABYLON || (BABYLON = {}));
  11601. var BABYLON;
  11602. (function (BABYLON) {
  11603. var FreeCameraMouseInput = (function () {
  11604. function FreeCameraMouseInput(touchEnabled) {
  11605. if (touchEnabled === void 0) { touchEnabled = true; }
  11606. this.touchEnabled = touchEnabled;
  11607. this.angularSensibility = 2000.0;
  11608. }
  11609. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11610. var _this = this;
  11611. if (!this._pointerInput) {
  11612. var camera = this.camera;
  11613. var engine = this.camera.getEngine();
  11614. this._pointerInput = function (p, s) {
  11615. var evt = p.event;
  11616. if (!_this.touchEnabled && evt.pointerType === "touch") {
  11617. return;
  11618. }
  11619. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11620. try {
  11621. evt.srcElement.setPointerCapture(evt.pointerId);
  11622. }
  11623. catch (e) {
  11624. }
  11625. _this.previousPosition = {
  11626. x: evt.clientX,
  11627. y: evt.clientY
  11628. };
  11629. if (!noPreventDefault) {
  11630. evt.preventDefault();
  11631. }
  11632. }
  11633. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11634. try {
  11635. evt.srcElement.releasePointerCapture(evt.pointerId);
  11636. }
  11637. catch (e) {
  11638. }
  11639. _this.previousPosition = null;
  11640. if (!noPreventDefault) {
  11641. evt.preventDefault();
  11642. }
  11643. }
  11644. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11645. if (!_this.previousPosition && !engine.isPointerLock) {
  11646. return;
  11647. }
  11648. var offsetX;
  11649. var offsetY;
  11650. if (!engine.isPointerLock) {
  11651. offsetX = evt.clientX - _this.previousPosition.x;
  11652. offsetY = evt.clientY - _this.previousPosition.y;
  11653. }
  11654. else {
  11655. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11656. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11657. }
  11658. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11659. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11660. _this.previousPosition = {
  11661. x: evt.clientX,
  11662. y: evt.clientY
  11663. };
  11664. if (!noPreventDefault) {
  11665. evt.preventDefault();
  11666. }
  11667. }
  11668. };
  11669. }
  11670. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11671. };
  11672. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11673. if (this._observer && element) {
  11674. this.camera.getScene().onPointerObservable.remove(this._observer);
  11675. this._observer = null;
  11676. this.previousPosition = null;
  11677. }
  11678. };
  11679. FreeCameraMouseInput.prototype.getTypeName = function () {
  11680. return "FreeCameraMouseInput";
  11681. };
  11682. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11683. return "mouse";
  11684. };
  11685. __decorate([
  11686. BABYLON.serialize()
  11687. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11688. return FreeCameraMouseInput;
  11689. })();
  11690. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11691. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11692. })(BABYLON || (BABYLON = {}));
  11693. var BABYLON;
  11694. (function (BABYLON) {
  11695. var FreeCameraKeyboardMoveInput = (function () {
  11696. function FreeCameraKeyboardMoveInput() {
  11697. this._keys = [];
  11698. this.keysUp = [38];
  11699. this.keysDown = [40];
  11700. this.keysLeft = [37];
  11701. this.keysRight = [39];
  11702. }
  11703. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11704. var _this = this;
  11705. if (!this._onKeyDown) {
  11706. this._onKeyDown = function (evt) {
  11707. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11708. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11709. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11710. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11711. var index = _this._keys.indexOf(evt.keyCode);
  11712. if (index === -1) {
  11713. _this._keys.push(evt.keyCode);
  11714. }
  11715. if (!noPreventDefault) {
  11716. evt.preventDefault();
  11717. }
  11718. }
  11719. };
  11720. this._onKeyUp = function (evt) {
  11721. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11722. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11723. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11724. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11725. var index = _this._keys.indexOf(evt.keyCode);
  11726. if (index >= 0) {
  11727. _this._keys.splice(index, 1);
  11728. }
  11729. if (!noPreventDefault) {
  11730. evt.preventDefault();
  11731. }
  11732. }
  11733. };
  11734. BABYLON.Tools.RegisterTopRootEvents([
  11735. { name: "keydown", handler: this._onKeyDown },
  11736. { name: "keyup", handler: this._onKeyUp },
  11737. { name: "blur", handler: this._onLostFocus }
  11738. ]);
  11739. }
  11740. };
  11741. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11742. if (this._onKeyDown) {
  11743. BABYLON.Tools.UnregisterTopRootEvents([
  11744. { name: "keydown", handler: this._onKeyDown },
  11745. { name: "keyup", handler: this._onKeyUp },
  11746. { name: "blur", handler: this._onLostFocus }
  11747. ]);
  11748. this._keys = [];
  11749. this._onKeyDown = null;
  11750. this._onKeyUp = null;
  11751. }
  11752. };
  11753. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11754. if (this._onKeyDown) {
  11755. var camera = this.camera;
  11756. // Keyboard
  11757. for (var index = 0; index < this._keys.length; index++) {
  11758. var keyCode = this._keys[index];
  11759. var speed = camera._computeLocalCameraSpeed();
  11760. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11761. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11762. }
  11763. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11764. camera._localDirection.copyFromFloats(0, 0, speed);
  11765. }
  11766. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11767. camera._localDirection.copyFromFloats(speed, 0, 0);
  11768. }
  11769. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11770. camera._localDirection.copyFromFloats(0, 0, -speed);
  11771. }
  11772. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11773. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11774. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11775. }
  11776. }
  11777. };
  11778. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11779. return "FreeCameraKeyboardMoveInput";
  11780. };
  11781. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11782. this._keys = [];
  11783. };
  11784. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11785. return "keyboard";
  11786. };
  11787. __decorate([
  11788. BABYLON.serialize()
  11789. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11790. __decorate([
  11791. BABYLON.serialize()
  11792. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11793. __decorate([
  11794. BABYLON.serialize()
  11795. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11796. __decorate([
  11797. BABYLON.serialize()
  11798. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11799. return FreeCameraKeyboardMoveInput;
  11800. })();
  11801. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11802. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11803. })(BABYLON || (BABYLON = {}));
  11804. var BABYLON;
  11805. (function (BABYLON) {
  11806. var FreeCameraTouchInput = (function () {
  11807. function FreeCameraTouchInput() {
  11808. this._offsetX = null;
  11809. this._offsetY = null;
  11810. this._pointerCount = 0;
  11811. this._pointerPressed = [];
  11812. this.touchAngularSensibility = 200000.0;
  11813. this.touchMoveSensibility = 250.0;
  11814. }
  11815. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11816. var _this = this;
  11817. var previousPosition;
  11818. if (this._pointerInput === undefined) {
  11819. this._onLostFocus = function (evt) {
  11820. _this._offsetX = null;
  11821. _this._offsetY = null;
  11822. };
  11823. this._pointerInput = function (p, s) {
  11824. var evt = p.event;
  11825. if (evt.pointerType === "mouse") {
  11826. return;
  11827. }
  11828. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11829. if (!noPreventDefault) {
  11830. evt.preventDefault();
  11831. }
  11832. _this._pointerPressed.push(evt.pointerId);
  11833. if (_this._pointerPressed.length !== 1) {
  11834. return;
  11835. }
  11836. previousPosition = {
  11837. x: evt.clientX,
  11838. y: evt.clientY
  11839. };
  11840. }
  11841. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11842. if (!noPreventDefault) {
  11843. evt.preventDefault();
  11844. }
  11845. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11846. if (index === -1) {
  11847. return;
  11848. }
  11849. _this._pointerPressed.splice(index, 1);
  11850. if (index != 0) {
  11851. return;
  11852. }
  11853. previousPosition = null;
  11854. _this._offsetX = null;
  11855. _this._offsetY = null;
  11856. }
  11857. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11858. if (!noPreventDefault) {
  11859. evt.preventDefault();
  11860. }
  11861. if (!previousPosition) {
  11862. return;
  11863. }
  11864. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11865. if (index != 0) {
  11866. return;
  11867. }
  11868. _this._offsetX = evt.clientX - previousPosition.x;
  11869. _this._offsetY = -(evt.clientY - previousPosition.y);
  11870. }
  11871. };
  11872. }
  11873. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11874. element.addEventListener("blur", this._onLostFocus);
  11875. };
  11876. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11877. if (this._pointerInput && element) {
  11878. this.camera.getScene().onPointerObservable.remove(this._observer);
  11879. this._observer = null;
  11880. element.removeEventListener("blur", this._onLostFocus);
  11881. this._onLostFocus = null;
  11882. this._pointerPressed = [];
  11883. this._offsetX = null;
  11884. this._offsetY = null;
  11885. this._pointerCount = 0;
  11886. }
  11887. };
  11888. FreeCameraTouchInput.prototype.checkInputs = function () {
  11889. if (this._offsetX) {
  11890. var camera = this.camera;
  11891. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11892. if (this._pointerPressed.length > 1) {
  11893. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11894. }
  11895. else {
  11896. var speed = camera._computeLocalCameraSpeed();
  11897. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11898. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11899. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11900. }
  11901. }
  11902. };
  11903. FreeCameraTouchInput.prototype.getTypeName = function () {
  11904. return "FreeCameraTouchInput";
  11905. };
  11906. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11907. return "touch";
  11908. };
  11909. __decorate([
  11910. BABYLON.serialize()
  11911. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11912. __decorate([
  11913. BABYLON.serialize()
  11914. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11915. return FreeCameraTouchInput;
  11916. })();
  11917. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11918. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11919. })(BABYLON || (BABYLON = {}));
  11920. var BABYLON;
  11921. (function (BABYLON) {
  11922. var FreeCameraDeviceOrientationInput = (function () {
  11923. function FreeCameraDeviceOrientationInput() {
  11924. this._offsetX = null;
  11925. this._offsetY = null;
  11926. this._orientationGamma = 0;
  11927. this._orientationBeta = 0;
  11928. this._initialOrientationGamma = 0;
  11929. this._initialOrientationBeta = 0;
  11930. this.angularSensibility = 10000.0;
  11931. this.moveSensibility = 50.0;
  11932. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11933. this._orientationChanged = this.orientationChanged.bind(this);
  11934. }
  11935. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11936. window.addEventListener("resize", this._resetOrientationGamma, false);
  11937. window.addEventListener("deviceorientation", this._orientationChanged);
  11938. };
  11939. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11940. this._initialOrientationGamma = null;
  11941. };
  11942. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11943. if (!this._initialOrientationGamma) {
  11944. this._initialOrientationGamma = evt.gamma;
  11945. this._initialOrientationBeta = evt.beta;
  11946. }
  11947. this._orientationGamma = evt.gamma;
  11948. this._orientationBeta = evt.beta;
  11949. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11950. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11951. };
  11952. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11953. window.removeEventListener("resize", this._resetOrientationGamma);
  11954. window.removeEventListener("deviceorientation", this._orientationChanged);
  11955. this._orientationGamma = 0;
  11956. this._orientationBeta = 0;
  11957. this._initialOrientationGamma = 0;
  11958. this._initialOrientationBeta = 0;
  11959. this._offsetX = null;
  11960. this._offsetY = null;
  11961. };
  11962. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11963. if (!this._offsetX) {
  11964. return;
  11965. }
  11966. var camera = this.camera;
  11967. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11968. var speed = camera._computeLocalCameraSpeed();
  11969. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11970. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11971. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11972. };
  11973. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11974. return "FreeCameraDeviceOrientationInput";
  11975. };
  11976. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11977. return "deviceOrientation";
  11978. };
  11979. __decorate([
  11980. BABYLON.serialize()
  11981. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11982. __decorate([
  11983. BABYLON.serialize()
  11984. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11985. return FreeCameraDeviceOrientationInput;
  11986. })();
  11987. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11988. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11989. })(BABYLON || (BABYLON = {}));
  11990. var BABYLON;
  11991. (function (BABYLON) {
  11992. var FreeCameraVRDeviceOrientationInput = (function () {
  11993. function FreeCameraVRDeviceOrientationInput() {
  11994. this.alphaCorrection = 1;
  11995. this.betaCorrection = 1;
  11996. this.gammaCorrection = 1;
  11997. this._alpha = 0;
  11998. this._beta = 0;
  11999. this._gamma = 0;
  12000. this._dirty = false;
  12001. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12002. }
  12003. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12004. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12005. };
  12006. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12007. var camera = this.camera;
  12008. this._alpha = +evt.alpha | 0;
  12009. this._beta = +evt.beta | 0;
  12010. this._gamma = +evt.gamma | 0;
  12011. this._dirty = true;
  12012. };
  12013. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12014. if (this._dirty) {
  12015. this._dirty = false;
  12016. var rotationX = this._gamma;
  12017. if (rotationX < 0) {
  12018. rotationX = 90 + rotationX;
  12019. }
  12020. else {
  12021. // Incline it in the correct angle.
  12022. rotationX = 270 - rotationX;
  12023. }
  12024. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12025. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12026. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12027. }
  12028. };
  12029. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12030. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12031. };
  12032. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12033. return "FreeCameraVRDeviceOrientationInput";
  12034. };
  12035. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12036. return "VRDeviceOrientation";
  12037. };
  12038. return FreeCameraVRDeviceOrientationInput;
  12039. })();
  12040. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12041. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12042. })(BABYLON || (BABYLON = {}));
  12043. var BABYLON;
  12044. (function (BABYLON) {
  12045. var FreeCameraGamepadInput = (function () {
  12046. function FreeCameraGamepadInput() {
  12047. this.gamepadAngularSensibility = 200;
  12048. this.gamepadMoveSensibility = 40;
  12049. }
  12050. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12051. var _this = this;
  12052. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12053. };
  12054. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12055. if (this._gamepads) {
  12056. this._gamepads.dispose();
  12057. }
  12058. this.gamepad = null;
  12059. };
  12060. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12061. if (this.gamepad) {
  12062. var camera = this.camera;
  12063. var LSValues = this.gamepad.leftStick;
  12064. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12065. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12066. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12067. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12068. var RSValues = this.gamepad.rightStick;
  12069. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12070. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12071. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12072. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12073. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12074. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12075. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12076. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12077. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12078. }
  12079. };
  12080. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12081. // Only the first gamepad can control the camera
  12082. if (gamepad.index === 0) {
  12083. this.gamepad = gamepad;
  12084. }
  12085. };
  12086. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12087. return "FreeCameraGamepadInput";
  12088. };
  12089. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12090. return "gamepad";
  12091. };
  12092. __decorate([
  12093. BABYLON.serialize()
  12094. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12095. __decorate([
  12096. BABYLON.serialize()
  12097. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12098. return FreeCameraGamepadInput;
  12099. })();
  12100. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12101. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12102. })(BABYLON || (BABYLON = {}));
  12103. var BABYLON;
  12104. (function (BABYLON) {
  12105. var FreeCameraVirtualJoystickInput = (function () {
  12106. function FreeCameraVirtualJoystickInput() {
  12107. }
  12108. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12109. return this._leftjoystick;
  12110. };
  12111. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12112. return this._rightjoystick;
  12113. };
  12114. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12115. if (this._leftjoystick) {
  12116. var camera = this.camera;
  12117. var speed = camera._computeLocalCameraSpeed() * 50;
  12118. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12119. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12120. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12121. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12122. if (!this._leftjoystick.pressed) {
  12123. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12124. }
  12125. if (!this._rightjoystick.pressed) {
  12126. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12127. }
  12128. }
  12129. };
  12130. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12131. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12132. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12133. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12134. this._leftjoystick.setJoystickSensibility(0.15);
  12135. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12136. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12137. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12138. this._rightjoystick.reverseUpDown = true;
  12139. this._rightjoystick.setJoystickSensibility(0.05);
  12140. this._rightjoystick.setJoystickColor("yellow");
  12141. };
  12142. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12143. this._leftjoystick.releaseCanvas();
  12144. this._rightjoystick.releaseCanvas();
  12145. };
  12146. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12147. return "FreeCameraVirtualJoystickInput";
  12148. };
  12149. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12150. return "virtualJoystick";
  12151. };
  12152. return FreeCameraVirtualJoystickInput;
  12153. })();
  12154. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12155. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12156. })(BABYLON || (BABYLON = {}));
  12157. var BABYLON;
  12158. (function (BABYLON) {
  12159. var ArcRotateCameraKeyboardMoveInput = (function () {
  12160. function ArcRotateCameraKeyboardMoveInput() {
  12161. this._keys = [];
  12162. this.keysUp = [38];
  12163. this.keysDown = [40];
  12164. this.keysLeft = [37];
  12165. this.keysRight = [39];
  12166. }
  12167. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12168. var _this = this;
  12169. this._onKeyDown = function (evt) {
  12170. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12171. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12172. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12173. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12174. var index = _this._keys.indexOf(evt.keyCode);
  12175. if (index === -1) {
  12176. _this._keys.push(evt.keyCode);
  12177. }
  12178. if (evt.preventDefault) {
  12179. if (!noPreventDefault) {
  12180. evt.preventDefault();
  12181. }
  12182. }
  12183. }
  12184. };
  12185. this._onKeyUp = function (evt) {
  12186. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12187. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12188. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12189. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12190. var index = _this._keys.indexOf(evt.keyCode);
  12191. if (index >= 0) {
  12192. _this._keys.splice(index, 1);
  12193. }
  12194. if (evt.preventDefault) {
  12195. if (!noPreventDefault) {
  12196. evt.preventDefault();
  12197. }
  12198. }
  12199. }
  12200. };
  12201. this._onLostFocus = function () {
  12202. _this._keys = [];
  12203. };
  12204. BABYLON.Tools.RegisterTopRootEvents([
  12205. { name: "keydown", handler: this._onKeyDown },
  12206. { name: "keyup", handler: this._onKeyUp },
  12207. { name: "blur", handler: this._onLostFocus }
  12208. ]);
  12209. };
  12210. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12211. BABYLON.Tools.UnregisterTopRootEvents([
  12212. { name: "keydown", handler: this._onKeyDown },
  12213. { name: "keyup", handler: this._onKeyUp },
  12214. { name: "blur", handler: this._onLostFocus }
  12215. ]);
  12216. this._keys = [];
  12217. this._onKeyDown = null;
  12218. this._onKeyUp = null;
  12219. this._onLostFocus = null;
  12220. };
  12221. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12222. if (this._onKeyDown) {
  12223. var camera = this.camera;
  12224. for (var index = 0; index < this._keys.length; index++) {
  12225. var keyCode = this._keys[index];
  12226. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12227. camera.inertialAlphaOffset -= 0.01;
  12228. }
  12229. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12230. camera.inertialBetaOffset -= 0.01;
  12231. }
  12232. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12233. camera.inertialAlphaOffset += 0.01;
  12234. }
  12235. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12236. camera.inertialBetaOffset += 0.01;
  12237. }
  12238. }
  12239. }
  12240. };
  12241. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12242. return "ArcRotateCameraKeyboardMoveInput";
  12243. };
  12244. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12245. return "keyboard";
  12246. };
  12247. __decorate([
  12248. BABYLON.serialize()
  12249. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12250. __decorate([
  12251. BABYLON.serialize()
  12252. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12253. __decorate([
  12254. BABYLON.serialize()
  12255. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12256. __decorate([
  12257. BABYLON.serialize()
  12258. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12259. return ArcRotateCameraKeyboardMoveInput;
  12260. })();
  12261. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12262. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12263. })(BABYLON || (BABYLON = {}));
  12264. var BABYLON;
  12265. (function (BABYLON) {
  12266. var ArcRotateCameraMouseWheelInput = (function () {
  12267. function ArcRotateCameraMouseWheelInput() {
  12268. this.wheelPrecision = 3.0;
  12269. }
  12270. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12271. var _this = this;
  12272. this._wheel = function (p, s) {
  12273. //sanity check - this should be a PointerWheel event.
  12274. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12275. return;
  12276. var event = p.event;
  12277. var delta = 0;
  12278. if (event.wheelDelta) {
  12279. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12280. }
  12281. else if (event.detail) {
  12282. delta = -event.detail / _this.wheelPrecision;
  12283. }
  12284. if (delta)
  12285. _this.camera.inertialRadiusOffset += delta;
  12286. if (event.preventDefault) {
  12287. if (!noPreventDefault) {
  12288. event.preventDefault();
  12289. }
  12290. }
  12291. };
  12292. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12293. };
  12294. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12295. if (this._observer && element) {
  12296. this.camera.getScene().onPointerObservable.remove(this._observer);
  12297. this._observer = null;
  12298. this._wheel = null;
  12299. }
  12300. };
  12301. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12302. return "ArcRotateCameraMouseWheelInput";
  12303. };
  12304. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12305. return "mousewheel";
  12306. };
  12307. __decorate([
  12308. BABYLON.serialize()
  12309. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12310. return ArcRotateCameraMouseWheelInput;
  12311. })();
  12312. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12313. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12314. })(BABYLON || (BABYLON = {}));
  12315. var BABYLON;
  12316. (function (BABYLON) {
  12317. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12318. var ArcRotateCameraPointersInput = (function () {
  12319. function ArcRotateCameraPointersInput() {
  12320. this.angularSensibilityX = 1000.0;
  12321. this.angularSensibilityY = 1000.0;
  12322. this.pinchPrecision = 6.0;
  12323. this.panningSensibility = 50.0;
  12324. this._isRightClick = false;
  12325. this._isCtrlPushed = false;
  12326. this.pinchInwards = true;
  12327. }
  12328. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12329. var _this = this;
  12330. var engine = this.camera.getEngine();
  12331. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12332. var pointers = new BABYLON.SmartCollection();
  12333. var previousPinchDistance = 0;
  12334. this._pointerInput = function (p, s) {
  12335. var evt = p.event;
  12336. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12337. try {
  12338. evt.srcElement.setPointerCapture(evt.pointerId);
  12339. }
  12340. catch (e) {
  12341. }
  12342. // Manage panning with right click
  12343. _this._isRightClick = evt.button === 2;
  12344. // manage pointers
  12345. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  12346. cacheSoloPointer = pointers.item(evt.pointerId);
  12347. if (!noPreventDefault) {
  12348. evt.preventDefault();
  12349. }
  12350. }
  12351. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12352. try {
  12353. evt.srcElement.releasePointerCapture(evt.pointerId);
  12354. }
  12355. catch (e) {
  12356. }
  12357. cacheSoloPointer = null;
  12358. previousPinchDistance = 0;
  12359. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12360. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12361. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12362. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12363. pointers.empty();
  12364. if (!noPreventDefault) {
  12365. evt.preventDefault();
  12366. }
  12367. }
  12368. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12369. if (!noPreventDefault) {
  12370. evt.preventDefault();
  12371. }
  12372. switch (pointers.count) {
  12373. case 1:
  12374. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12375. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12376. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12377. }
  12378. else {
  12379. var offsetX = evt.clientX - cacheSoloPointer.x;
  12380. var offsetY = evt.clientY - cacheSoloPointer.y;
  12381. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12382. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12383. }
  12384. cacheSoloPointer.x = evt.clientX;
  12385. cacheSoloPointer.y = evt.clientY;
  12386. break;
  12387. case 2:
  12388. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12389. pointers.item(evt.pointerId).x = evt.clientX;
  12390. pointers.item(evt.pointerId).y = evt.clientY;
  12391. var direction = _this.pinchInwards ? 1 : -1;
  12392. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  12393. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  12394. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12395. if (previousPinchDistance === 0) {
  12396. previousPinchDistance = pinchSquaredDistance;
  12397. return;
  12398. }
  12399. if (pinchSquaredDistance !== previousPinchDistance) {
  12400. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12401. previousPinchDistance = pinchSquaredDistance;
  12402. }
  12403. break;
  12404. default:
  12405. if (pointers.item(evt.pointerId)) {
  12406. pointers.item(evt.pointerId).x = evt.clientX;
  12407. pointers.item(evt.pointerId).y = evt.clientY;
  12408. }
  12409. }
  12410. }
  12411. };
  12412. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12413. this._onContextMenu = function (evt) {
  12414. evt.preventDefault();
  12415. };
  12416. if (!this.camera._useCtrlForPanning) {
  12417. element.addEventListener("contextmenu", this._onContextMenu, false);
  12418. }
  12419. this._onLostFocus = function () {
  12420. //this._keys = [];
  12421. pointers.empty();
  12422. previousPinchDistance = 0;
  12423. cacheSoloPointer = null;
  12424. };
  12425. this._onKeyDown = function (evt) {
  12426. _this._isCtrlPushed = evt.ctrlKey;
  12427. };
  12428. this._onKeyUp = function (evt) {
  12429. _this._isCtrlPushed = evt.ctrlKey;
  12430. };
  12431. this._onMouseMove = function (evt) {
  12432. if (!engine.isPointerLock) {
  12433. return;
  12434. }
  12435. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12436. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12437. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12438. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12439. if (!noPreventDefault) {
  12440. evt.preventDefault();
  12441. }
  12442. };
  12443. this._onGestureStart = function (e) {
  12444. if (window.MSGesture === undefined) {
  12445. return;
  12446. }
  12447. if (!_this._MSGestureHandler) {
  12448. _this._MSGestureHandler = new MSGesture();
  12449. _this._MSGestureHandler.target = element;
  12450. }
  12451. _this._MSGestureHandler.addPointer(e.pointerId);
  12452. };
  12453. this._onGesture = function (e) {
  12454. _this.camera.radius *= e.scale;
  12455. if (e.preventDefault) {
  12456. if (!noPreventDefault) {
  12457. e.stopPropagation();
  12458. e.preventDefault();
  12459. }
  12460. }
  12461. };
  12462. element.addEventListener("mousemove", this._onMouseMove, false);
  12463. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12464. element.addEventListener("MSGestureChange", this._onGesture, false);
  12465. BABYLON.Tools.RegisterTopRootEvents([
  12466. { name: "keydown", handler: this._onKeyDown },
  12467. { name: "keyup", handler: this._onKeyUp },
  12468. { name: "blur", handler: this._onLostFocus }
  12469. ]);
  12470. };
  12471. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12472. if (element && this._observer) {
  12473. this.camera.getScene().onPointerObservable.remove(this._observer);
  12474. this._observer = null;
  12475. element.removeEventListener("contextmenu", this._onContextMenu);
  12476. element.removeEventListener("mousemove", this._onMouseMove);
  12477. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12478. element.removeEventListener("MSGestureChange", this._onGesture);
  12479. this._isRightClick = false;
  12480. this._isCtrlPushed = false;
  12481. this.pinchInwards = true;
  12482. this._onKeyDown = null;
  12483. this._onKeyUp = null;
  12484. this._onMouseMove = null;
  12485. this._onGestureStart = null;
  12486. this._onGesture = null;
  12487. this._MSGestureHandler = null;
  12488. this._onLostFocus = null;
  12489. this._onContextMenu = null;
  12490. }
  12491. BABYLON.Tools.UnregisterTopRootEvents([
  12492. { name: "keydown", handler: this._onKeyDown },
  12493. { name: "keyup", handler: this._onKeyUp },
  12494. { name: "blur", handler: this._onLostFocus }
  12495. ]);
  12496. };
  12497. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12498. return "ArcRotateCameraPointersInput";
  12499. };
  12500. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12501. return "pointers";
  12502. };
  12503. __decorate([
  12504. BABYLON.serialize()
  12505. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12506. __decorate([
  12507. BABYLON.serialize()
  12508. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12509. __decorate([
  12510. BABYLON.serialize()
  12511. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12512. __decorate([
  12513. BABYLON.serialize()
  12514. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12515. return ArcRotateCameraPointersInput;
  12516. })();
  12517. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12518. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12519. })(BABYLON || (BABYLON = {}));
  12520. var BABYLON;
  12521. (function (BABYLON) {
  12522. var ArcRotateCameraGamepadInput = (function () {
  12523. function ArcRotateCameraGamepadInput() {
  12524. this.gamepadRotationSensibility = 80;
  12525. this.gamepadMoveSensibility = 40;
  12526. }
  12527. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12528. var _this = this;
  12529. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12530. };
  12531. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12532. if (this._gamepads) {
  12533. this._gamepads.dispose();
  12534. }
  12535. this.gamepad = null;
  12536. };
  12537. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12538. if (this.gamepad) {
  12539. var camera = this.camera;
  12540. var RSValues = this.gamepad.rightStick;
  12541. if (RSValues.x != 0) {
  12542. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12543. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12544. camera.inertialAlphaOffset += normalizedRX;
  12545. }
  12546. }
  12547. if (RSValues.y != 0) {
  12548. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12549. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12550. camera.inertialBetaOffset += normalizedRY;
  12551. }
  12552. }
  12553. var LSValues = this.gamepad.leftStick;
  12554. if (LSValues.y != 0) {
  12555. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12556. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12557. this.camera.inertialRadiusOffset -= normalizedLY;
  12558. }
  12559. }
  12560. }
  12561. };
  12562. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12563. // Only the first gamepad can control the camera
  12564. if (gamepad.index === 0) {
  12565. this.gamepad = gamepad;
  12566. }
  12567. };
  12568. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12569. return "ArcRotateCameraGamepadInput";
  12570. };
  12571. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12572. return "gamepad";
  12573. };
  12574. __decorate([
  12575. BABYLON.serialize()
  12576. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12577. __decorate([
  12578. BABYLON.serialize()
  12579. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12580. return ArcRotateCameraGamepadInput;
  12581. })();
  12582. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12583. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12584. })(BABYLON || (BABYLON = {}));
  12585. var BABYLON;
  12586. (function (BABYLON) {
  12587. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12588. function ArcRotateCameraVRDeviceOrientationInput() {
  12589. this.alphaCorrection = 1;
  12590. this.betaCorrection = 1;
  12591. this.gammaCorrection = 1;
  12592. this._alpha = 0;
  12593. this._beta = 0;
  12594. this._gamma = 0;
  12595. this._dirty = false;
  12596. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12597. }
  12598. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12599. this.camera.attachControl(element, noPreventDefault);
  12600. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12601. };
  12602. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12603. var camera = this.camera;
  12604. this._alpha = +evt.alpha | 0;
  12605. this._beta = +evt.beta | 0;
  12606. this._gamma = +evt.gamma | 0;
  12607. this._dirty = true;
  12608. };
  12609. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12610. if (this._dirty) {
  12611. this._dirty = false;
  12612. if (this._gamma < 0) {
  12613. this._gamma = 180 + this._gamma;
  12614. }
  12615. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12616. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12617. }
  12618. };
  12619. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12620. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12621. };
  12622. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12623. return "ArcRotateCameraVRDeviceOrientationInput";
  12624. };
  12625. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12626. return "VRDeviceOrientation";
  12627. };
  12628. return ArcRotateCameraVRDeviceOrientationInput;
  12629. })();
  12630. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12631. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12632. })(BABYLON || (BABYLON = {}));
  12633. var BABYLON;
  12634. (function (BABYLON) {
  12635. var TargetCamera = (function (_super) {
  12636. __extends(TargetCamera, _super);
  12637. function TargetCamera(name, position, scene) {
  12638. _super.call(this, name, position, scene);
  12639. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12640. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12641. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12642. this.speed = 2.0;
  12643. this.noRotationConstraint = false;
  12644. this.lockedTarget = null;
  12645. this._currentTarget = BABYLON.Vector3.Zero();
  12646. this._viewMatrix = BABYLON.Matrix.Zero();
  12647. this._camMatrix = BABYLON.Matrix.Zero();
  12648. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12649. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12650. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12651. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12652. this._lookAtTemp = BABYLON.Matrix.Zero();
  12653. this._tempMatrix = BABYLON.Matrix.Zero();
  12654. }
  12655. TargetCamera.prototype.getFrontPosition = function (distance) {
  12656. var direction = this.getTarget().subtract(this.position);
  12657. direction.normalize();
  12658. direction.scaleInPlace(distance);
  12659. return this.globalPosition.add(direction);
  12660. };
  12661. TargetCamera.prototype._getLockedTargetPosition = function () {
  12662. if (!this.lockedTarget) {
  12663. return null;
  12664. }
  12665. return this.lockedTarget.position || this.lockedTarget;
  12666. };
  12667. // Cache
  12668. TargetCamera.prototype._initCache = function () {
  12669. _super.prototype._initCache.call(this);
  12670. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12671. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12672. };
  12673. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12674. if (!ignoreParentClass) {
  12675. _super.prototype._updateCache.call(this);
  12676. }
  12677. var lockedTargetPosition = this._getLockedTargetPosition();
  12678. if (!lockedTargetPosition) {
  12679. this._cache.lockedTarget = null;
  12680. }
  12681. else {
  12682. if (!this._cache.lockedTarget) {
  12683. this._cache.lockedTarget = lockedTargetPosition.clone();
  12684. }
  12685. else {
  12686. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12687. }
  12688. }
  12689. this._cache.rotation.copyFrom(this.rotation);
  12690. };
  12691. // Synchronized
  12692. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12693. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12694. return false;
  12695. }
  12696. var lockedTargetPosition = this._getLockedTargetPosition();
  12697. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12698. && this._cache.rotation.equals(this.rotation);
  12699. };
  12700. // Methods
  12701. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12702. var engine = this.getEngine();
  12703. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12704. };
  12705. // Target
  12706. TargetCamera.prototype.setTarget = function (target) {
  12707. this.upVector.normalize();
  12708. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12709. this._camMatrix.invert();
  12710. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12711. var vDir = target.subtract(this.position);
  12712. if (vDir.x >= 0.0) {
  12713. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12714. }
  12715. else {
  12716. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12717. }
  12718. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12719. if (isNaN(this.rotation.x)) {
  12720. this.rotation.x = 0;
  12721. }
  12722. if (isNaN(this.rotation.y)) {
  12723. this.rotation.y = 0;
  12724. }
  12725. if (isNaN(this.rotation.z)) {
  12726. this.rotation.z = 0;
  12727. }
  12728. };
  12729. TargetCamera.prototype.getTarget = function () {
  12730. return this._currentTarget;
  12731. };
  12732. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12733. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12734. };
  12735. TargetCamera.prototype._updatePosition = function () {
  12736. this.position.addInPlace(this.cameraDirection);
  12737. };
  12738. TargetCamera.prototype._checkInputs = function () {
  12739. var needToMove = this._decideIfNeedsToMove();
  12740. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12741. // Move
  12742. if (needToMove) {
  12743. this._updatePosition();
  12744. }
  12745. // Rotate
  12746. if (needToRotate) {
  12747. this.rotation.x += this.cameraRotation.x;
  12748. this.rotation.y += this.cameraRotation.y;
  12749. if (!this.noRotationConstraint) {
  12750. var limit = (Math.PI / 2) * 0.95;
  12751. if (this.rotation.x > limit)
  12752. this.rotation.x = limit;
  12753. if (this.rotation.x < -limit)
  12754. this.rotation.x = -limit;
  12755. }
  12756. }
  12757. // Inertia
  12758. if (needToMove) {
  12759. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12760. this.cameraDirection.x = 0;
  12761. }
  12762. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12763. this.cameraDirection.y = 0;
  12764. }
  12765. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12766. this.cameraDirection.z = 0;
  12767. }
  12768. this.cameraDirection.scaleInPlace(this.inertia);
  12769. }
  12770. if (needToRotate) {
  12771. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12772. this.cameraRotation.x = 0;
  12773. }
  12774. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12775. this.cameraRotation.y = 0;
  12776. }
  12777. this.cameraRotation.scaleInPlace(this.inertia);
  12778. }
  12779. _super.prototype._checkInputs.call(this);
  12780. };
  12781. TargetCamera.prototype._getViewMatrix = function () {
  12782. if (!this.lockedTarget) {
  12783. // Compute
  12784. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12785. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12786. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12787. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12788. this._lookAtTemp.invert();
  12789. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12790. }
  12791. else {
  12792. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12793. }
  12794. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12795. // Computing target and final matrix
  12796. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12797. }
  12798. else {
  12799. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12800. }
  12801. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12802. return this._viewMatrix;
  12803. };
  12804. TargetCamera.prototype._getVRViewMatrix = function () {
  12805. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12806. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12807. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12808. // Computing target and final matrix
  12809. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12810. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12811. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12812. return this._viewMatrix;
  12813. };
  12814. /**
  12815. * @override
  12816. * Override Camera.createRigCamera
  12817. */
  12818. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12819. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12820. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12821. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12822. rigCamera._cameraRigParams = {};
  12823. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12824. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12825. }
  12826. return rigCamera;
  12827. }
  12828. return null;
  12829. };
  12830. /**
  12831. * @override
  12832. * Override Camera._updateRigCameras
  12833. */
  12834. TargetCamera.prototype._updateRigCameras = function () {
  12835. switch (this.cameraRigMode) {
  12836. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12837. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12838. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12839. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12840. case BABYLON.Camera.RIG_MODE_VR:
  12841. var camLeft = this._rigCameras[0];
  12842. var camRight = this._rigCameras[1];
  12843. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12844. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12845. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12846. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12847. camLeft.position.copyFrom(this.position);
  12848. camRight.position.copyFrom(this.position);
  12849. }
  12850. else {
  12851. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12852. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12853. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12854. camLeft.setTarget(this.getTarget());
  12855. camRight.setTarget(this.getTarget());
  12856. }
  12857. break;
  12858. }
  12859. _super.prototype._updateRigCameras.call(this);
  12860. };
  12861. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12862. if (!this._rigCamTransformMatrix) {
  12863. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12864. }
  12865. var target = this.getTarget();
  12866. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12867. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12868. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12869. };
  12870. TargetCamera.prototype.getTypeName = function () {
  12871. return "TargetCamera";
  12872. };
  12873. __decorate([
  12874. BABYLON.serializeAsVector3()
  12875. ], TargetCamera.prototype, "rotation", void 0);
  12876. __decorate([
  12877. BABYLON.serialize()
  12878. ], TargetCamera.prototype, "speed", void 0);
  12879. __decorate([
  12880. BABYLON.serializeAsMeshReference("lockedTargetId")
  12881. ], TargetCamera.prototype, "lockedTarget", void 0);
  12882. return TargetCamera;
  12883. })(BABYLON.Camera);
  12884. BABYLON.TargetCamera = TargetCamera;
  12885. })(BABYLON || (BABYLON = {}));
  12886. var BABYLON;
  12887. (function (BABYLON) {
  12888. var FreeCamera = (function (_super) {
  12889. __extends(FreeCamera, _super);
  12890. function FreeCamera(name, position, scene) {
  12891. var _this = this;
  12892. _super.call(this, name, position, scene);
  12893. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12894. this.checkCollisions = false;
  12895. this.applyGravity = false;
  12896. this._collider = new BABYLON.Collider();
  12897. this._needMoveForGravity = false;
  12898. this._oldPosition = BABYLON.Vector3.Zero();
  12899. this._diffPosition = BABYLON.Vector3.Zero();
  12900. this._newPosition = BABYLON.Vector3.Zero();
  12901. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12902. if (collidedMesh === void 0) { collidedMesh = null; }
  12903. //TODO move this to the collision coordinator!
  12904. if (_this.getScene().workerCollisions)
  12905. newPosition.multiplyInPlace(_this._collider.radius);
  12906. var updatePosition = function (newPos) {
  12907. _this._newPosition.copyFrom(newPos);
  12908. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12909. var oldPosition = _this.position.clone();
  12910. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12911. _this.position.addInPlace(_this._diffPosition);
  12912. if (_this.onCollide && collidedMesh) {
  12913. _this.onCollide(collidedMesh);
  12914. }
  12915. }
  12916. };
  12917. updatePosition(newPosition);
  12918. };
  12919. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12920. this.inputs.addKeyboard().addMouse();
  12921. }
  12922. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12923. //-- begin properties for backward compatibility for inputs
  12924. get: function () {
  12925. var mouse = this.inputs.attached["mouse"];
  12926. if (mouse)
  12927. return mouse.angularSensibility;
  12928. },
  12929. set: function (value) {
  12930. var mouse = this.inputs.attached["mouse"];
  12931. if (mouse)
  12932. mouse.angularSensibility = value;
  12933. },
  12934. enumerable: true,
  12935. configurable: true
  12936. });
  12937. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12938. get: function () {
  12939. var keyboard = this.inputs.attached["keyboard"];
  12940. if (keyboard)
  12941. return keyboard.keysUp;
  12942. },
  12943. set: function (value) {
  12944. var keyboard = this.inputs.attached["keyboard"];
  12945. if (keyboard)
  12946. keyboard.keysUp = value;
  12947. },
  12948. enumerable: true,
  12949. configurable: true
  12950. });
  12951. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12952. get: function () {
  12953. var keyboard = this.inputs.attached["keyboard"];
  12954. if (keyboard)
  12955. return keyboard.keysDown;
  12956. },
  12957. set: function (value) {
  12958. var keyboard = this.inputs.attached["keyboard"];
  12959. if (keyboard)
  12960. keyboard.keysDown = value;
  12961. },
  12962. enumerable: true,
  12963. configurable: true
  12964. });
  12965. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12966. get: function () {
  12967. var keyboard = this.inputs.attached["keyboard"];
  12968. if (keyboard)
  12969. return keyboard.keysLeft;
  12970. },
  12971. set: function (value) {
  12972. var keyboard = this.inputs.attached["keyboard"];
  12973. if (keyboard)
  12974. keyboard.keysLeft = value;
  12975. },
  12976. enumerable: true,
  12977. configurable: true
  12978. });
  12979. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12980. get: function () {
  12981. var keyboard = this.inputs.attached["keyboard"];
  12982. if (keyboard)
  12983. return keyboard.keysRight;
  12984. },
  12985. set: function (value) {
  12986. var keyboard = this.inputs.attached["keyboard"];
  12987. if (keyboard)
  12988. keyboard.keysRight = value;
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. // Controls
  12994. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12995. this.inputs.attachElement(element, noPreventDefault);
  12996. };
  12997. FreeCamera.prototype.detachControl = function (element) {
  12998. this.inputs.detachElement(element);
  12999. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13000. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13001. };
  13002. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13003. var globalPosition;
  13004. if (this.parent) {
  13005. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13006. }
  13007. else {
  13008. globalPosition = this.position;
  13009. }
  13010. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13011. this._collider.radius = this.ellipsoid;
  13012. //no need for clone, as long as gravity is not on.
  13013. var actualVelocity = velocity;
  13014. //add gravity to the velocity to prevent the dual-collision checking
  13015. if (this.applyGravity) {
  13016. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13017. actualVelocity = velocity.add(this.getScene().gravity);
  13018. }
  13019. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13020. };
  13021. FreeCamera.prototype._checkInputs = function () {
  13022. if (!this._localDirection) {
  13023. this._localDirection = BABYLON.Vector3.Zero();
  13024. this._transformedDirection = BABYLON.Vector3.Zero();
  13025. }
  13026. this.inputs.checkInputs();
  13027. _super.prototype._checkInputs.call(this);
  13028. };
  13029. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13030. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13031. };
  13032. FreeCamera.prototype._updatePosition = function () {
  13033. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13034. this._collideWithWorld(this.cameraDirection);
  13035. }
  13036. else {
  13037. this.position.addInPlace(this.cameraDirection);
  13038. }
  13039. };
  13040. FreeCamera.prototype.dispose = function () {
  13041. this.inputs.clear();
  13042. _super.prototype.dispose.call(this);
  13043. };
  13044. FreeCamera.prototype.getTypeName = function () {
  13045. return "FreeCamera";
  13046. };
  13047. __decorate([
  13048. BABYLON.serializeAsVector3()
  13049. ], FreeCamera.prototype, "ellipsoid", void 0);
  13050. __decorate([
  13051. BABYLON.serialize()
  13052. ], FreeCamera.prototype, "checkCollisions", void 0);
  13053. __decorate([
  13054. BABYLON.serialize()
  13055. ], FreeCamera.prototype, "applyGravity", void 0);
  13056. return FreeCamera;
  13057. })(BABYLON.TargetCamera);
  13058. BABYLON.FreeCamera = FreeCamera;
  13059. })(BABYLON || (BABYLON = {}));
  13060. var BABYLON;
  13061. (function (BABYLON) {
  13062. var FreeCameraInputsManager = (function (_super) {
  13063. __extends(FreeCameraInputsManager, _super);
  13064. function FreeCameraInputsManager(camera) {
  13065. _super.call(this, camera);
  13066. }
  13067. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13068. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13069. return this;
  13070. };
  13071. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13072. if (touchEnabled === void 0) { touchEnabled = true; }
  13073. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13074. return this;
  13075. };
  13076. FreeCameraInputsManager.prototype.addGamepad = function () {
  13077. this.add(new BABYLON.FreeCameraGamepadInput());
  13078. return this;
  13079. };
  13080. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13081. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13082. return this;
  13083. };
  13084. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13085. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13086. return this;
  13087. };
  13088. FreeCameraInputsManager.prototype.addTouch = function () {
  13089. this.add(new BABYLON.FreeCameraTouchInput());
  13090. return this;
  13091. };
  13092. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13093. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13094. return this;
  13095. };
  13096. return FreeCameraInputsManager;
  13097. })(BABYLON.CameraInputsManager);
  13098. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13099. })(BABYLON || (BABYLON = {}));
  13100. var BABYLON;
  13101. (function (BABYLON) {
  13102. var FollowCamera = (function (_super) {
  13103. __extends(FollowCamera, _super);
  13104. function FollowCamera(name, position, scene, target) {
  13105. _super.call(this, name, position, scene);
  13106. this.radius = 12;
  13107. this.rotationOffset = 0;
  13108. this.heightOffset = 4;
  13109. this.cameraAcceleration = 0.05;
  13110. this.maxCameraSpeed = 20;
  13111. this.target = target;
  13112. }
  13113. FollowCamera.prototype.getRadians = function (degrees) {
  13114. return degrees * Math.PI / 180;
  13115. };
  13116. FollowCamera.prototype.follow = function (cameraTarget) {
  13117. if (!cameraTarget)
  13118. return;
  13119. var yRotation;
  13120. if (cameraTarget.rotationQuaternion) {
  13121. var rotMatrix = new BABYLON.Matrix();
  13122. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13123. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13124. }
  13125. else {
  13126. yRotation = cameraTarget.rotation.y;
  13127. }
  13128. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13129. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13130. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13131. var dx = targetX - this.position.x;
  13132. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13133. var dz = (targetZ) - this.position.z;
  13134. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13135. var vy = dy * this.cameraAcceleration;
  13136. var vz = dz * this.cameraAcceleration * 2;
  13137. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13138. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13139. }
  13140. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13141. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13142. }
  13143. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13144. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13145. }
  13146. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13147. this.setTarget(cameraTarget.position);
  13148. };
  13149. FollowCamera.prototype._checkInputs = function () {
  13150. _super.prototype._checkInputs.call(this);
  13151. this.follow(this.target);
  13152. };
  13153. FollowCamera.prototype.getTypeName = function () {
  13154. return "FollowCamera";
  13155. };
  13156. __decorate([
  13157. BABYLON.serialize()
  13158. ], FollowCamera.prototype, "radius", void 0);
  13159. __decorate([
  13160. BABYLON.serialize()
  13161. ], FollowCamera.prototype, "rotationOffset", void 0);
  13162. __decorate([
  13163. BABYLON.serialize()
  13164. ], FollowCamera.prototype, "heightOffset", void 0);
  13165. __decorate([
  13166. BABYLON.serialize()
  13167. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13168. __decorate([
  13169. BABYLON.serialize()
  13170. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13171. __decorate([
  13172. BABYLON.serializeAsMeshReference("lockedTargetId")
  13173. ], FollowCamera.prototype, "target", void 0);
  13174. return FollowCamera;
  13175. })(BABYLON.TargetCamera);
  13176. BABYLON.FollowCamera = FollowCamera;
  13177. var ArcFollowCamera = (function (_super) {
  13178. __extends(ArcFollowCamera, _super);
  13179. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13180. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13181. this.alpha = alpha;
  13182. this.beta = beta;
  13183. this.radius = radius;
  13184. this.target = target;
  13185. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13186. this.follow();
  13187. }
  13188. ArcFollowCamera.prototype.follow = function () {
  13189. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13190. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13191. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13192. this.position = this.target.position.add(this._cartesianCoordinates);
  13193. this.setTarget(this.target.position);
  13194. };
  13195. ArcFollowCamera.prototype._checkInputs = function () {
  13196. _super.prototype._checkInputs.call(this);
  13197. this.follow();
  13198. };
  13199. ArcFollowCamera.prototype.getTypeName = function () {
  13200. return "ArcFollowCamera";
  13201. };
  13202. return ArcFollowCamera;
  13203. })(BABYLON.TargetCamera);
  13204. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13205. })(BABYLON || (BABYLON = {}));
  13206. var BABYLON;
  13207. (function (BABYLON) {
  13208. // We're mainly based on the logic defined into the FreeCamera code
  13209. var TouchCamera = (function (_super) {
  13210. __extends(TouchCamera, _super);
  13211. //-- end properties for backward compatibility for inputs
  13212. function TouchCamera(name, position, scene) {
  13213. _super.call(this, name, position, scene);
  13214. this.inputs.addTouch();
  13215. this._setupInputs();
  13216. }
  13217. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13218. //-- Begin properties for backward compatibility for inputs
  13219. get: function () {
  13220. var touch = this.inputs.attached["touch"];
  13221. if (touch)
  13222. return touch.touchAngularSensibility;
  13223. },
  13224. set: function (value) {
  13225. var touch = this.inputs.attached["touch"];
  13226. if (touch)
  13227. touch.touchAngularSensibility = value;
  13228. },
  13229. enumerable: true,
  13230. configurable: true
  13231. });
  13232. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13233. get: function () {
  13234. var touch = this.inputs.attached["touch"];
  13235. if (touch)
  13236. return touch.touchMoveSensibility;
  13237. },
  13238. set: function (value) {
  13239. var touch = this.inputs.attached["touch"];
  13240. if (touch)
  13241. touch.touchMoveSensibility = value;
  13242. },
  13243. enumerable: true,
  13244. configurable: true
  13245. });
  13246. TouchCamera.prototype.getTypeName = function () {
  13247. return "TouchCamera";
  13248. };
  13249. TouchCamera.prototype._setupInputs = function () {
  13250. var mouse = this.inputs.attached["mouse"];
  13251. if (mouse) {
  13252. mouse.touchEnabled = false;
  13253. }
  13254. };
  13255. return TouchCamera;
  13256. })(BABYLON.FreeCamera);
  13257. BABYLON.TouchCamera = TouchCamera;
  13258. })(BABYLON || (BABYLON = {}));
  13259. var BABYLON;
  13260. (function (BABYLON) {
  13261. var ArcRotateCamera = (function (_super) {
  13262. __extends(ArcRotateCamera, _super);
  13263. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13264. var _this = this;
  13265. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13266. this.inertialAlphaOffset = 0;
  13267. this.inertialBetaOffset = 0;
  13268. this.inertialRadiusOffset = 0;
  13269. this.lowerAlphaLimit = null;
  13270. this.upperAlphaLimit = null;
  13271. this.lowerBetaLimit = 0.01;
  13272. this.upperBetaLimit = Math.PI;
  13273. this.lowerRadiusLimit = null;
  13274. this.upperRadiusLimit = null;
  13275. this.inertialPanningX = 0;
  13276. this.inertialPanningY = 0;
  13277. //-- end properties for backward compatibility for inputs
  13278. this.zoomOnFactor = 1;
  13279. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13280. this.allowUpsideDown = true;
  13281. this._viewMatrix = new BABYLON.Matrix();
  13282. // Panning
  13283. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13284. this.checkCollisions = false;
  13285. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13286. this._collider = new BABYLON.Collider();
  13287. this._previousPosition = BABYLON.Vector3.Zero();
  13288. this._collisionVelocity = BABYLON.Vector3.Zero();
  13289. this._newPosition = BABYLON.Vector3.Zero();
  13290. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13291. if (collidedMesh === void 0) { collidedMesh = null; }
  13292. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13293. newPosition.multiplyInPlace(_this._collider.radius);
  13294. }
  13295. if (!collidedMesh) {
  13296. _this._previousPosition.copyFrom(_this.position);
  13297. }
  13298. else {
  13299. _this.setPosition(newPosition);
  13300. if (_this.onCollide) {
  13301. _this.onCollide(collidedMesh);
  13302. }
  13303. }
  13304. // Recompute because of constraints
  13305. var cosa = Math.cos(_this.alpha);
  13306. var sina = Math.sin(_this.alpha);
  13307. var cosb = Math.cos(_this.beta);
  13308. var sinb = Math.sin(_this.beta);
  13309. if (sinb === 0) {
  13310. sinb = 0.0001;
  13311. }
  13312. var target = _this._getTargetPosition();
  13313. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13314. _this.position.copyFrom(_this._newPosition);
  13315. var up = _this.upVector;
  13316. if (_this.allowUpsideDown && _this.beta < 0) {
  13317. up = up.clone();
  13318. up = up.negate();
  13319. }
  13320. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13321. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13322. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13323. _this._collisionTriggered = false;
  13324. };
  13325. if (!target) {
  13326. this.target = BABYLON.Vector3.Zero();
  13327. }
  13328. else {
  13329. this.target = target;
  13330. }
  13331. this.alpha = alpha;
  13332. this.beta = beta;
  13333. this.radius = radius;
  13334. this.getViewMatrix();
  13335. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13336. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13337. }
  13338. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13339. //-- begin properties for backward compatibility for inputs
  13340. get: function () {
  13341. var pointers = this.inputs.attached["pointers"];
  13342. if (pointers)
  13343. return pointers.angularSensibilityX;
  13344. },
  13345. set: function (value) {
  13346. var pointers = this.inputs.attached["pointers"];
  13347. if (pointers) {
  13348. pointers.angularSensibilityX = value;
  13349. }
  13350. },
  13351. enumerable: true,
  13352. configurable: true
  13353. });
  13354. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13355. get: function () {
  13356. var pointers = this.inputs.attached["pointers"];
  13357. if (pointers)
  13358. return pointers.angularSensibilityY;
  13359. },
  13360. set: function (value) {
  13361. var pointers = this.inputs.attached["pointers"];
  13362. if (pointers) {
  13363. pointers.angularSensibilityY = value;
  13364. }
  13365. },
  13366. enumerable: true,
  13367. configurable: true
  13368. });
  13369. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13370. get: function () {
  13371. var pointers = this.inputs.attached["pointers"];
  13372. if (pointers)
  13373. return pointers.pinchPrecision;
  13374. },
  13375. set: function (value) {
  13376. var pointers = this.inputs.attached["pointers"];
  13377. if (pointers) {
  13378. pointers.pinchPrecision = value;
  13379. }
  13380. },
  13381. enumerable: true,
  13382. configurable: true
  13383. });
  13384. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13385. get: function () {
  13386. var pointers = this.inputs.attached["pointers"];
  13387. if (pointers)
  13388. return pointers.panningSensibility;
  13389. },
  13390. set: function (value) {
  13391. var pointers = this.inputs.attached["pointers"];
  13392. if (pointers) {
  13393. pointers.panningSensibility = value;
  13394. }
  13395. },
  13396. enumerable: true,
  13397. configurable: true
  13398. });
  13399. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13400. get: function () {
  13401. var keyboard = this.inputs.attached["keyboard"];
  13402. if (keyboard)
  13403. return keyboard.keysUp;
  13404. },
  13405. set: function (value) {
  13406. var keyboard = this.inputs.attached["keyboard"];
  13407. if (keyboard)
  13408. keyboard.keysUp = value;
  13409. },
  13410. enumerable: true,
  13411. configurable: true
  13412. });
  13413. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13414. get: function () {
  13415. var keyboard = this.inputs.attached["keyboard"];
  13416. if (keyboard)
  13417. return keyboard.keysDown;
  13418. },
  13419. set: function (value) {
  13420. var keyboard = this.inputs.attached["keyboard"];
  13421. if (keyboard)
  13422. keyboard.keysDown = value;
  13423. },
  13424. enumerable: true,
  13425. configurable: true
  13426. });
  13427. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13428. get: function () {
  13429. var keyboard = this.inputs.attached["keyboard"];
  13430. if (keyboard)
  13431. return keyboard.keysLeft;
  13432. },
  13433. set: function (value) {
  13434. var keyboard = this.inputs.attached["keyboard"];
  13435. if (keyboard)
  13436. keyboard.keysLeft = value;
  13437. },
  13438. enumerable: true,
  13439. configurable: true
  13440. });
  13441. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13442. get: function () {
  13443. var keyboard = this.inputs.attached["keyboard"];
  13444. if (keyboard)
  13445. return keyboard.keysRight;
  13446. },
  13447. set: function (value) {
  13448. var keyboard = this.inputs.attached["keyboard"];
  13449. if (keyboard)
  13450. keyboard.keysRight = value;
  13451. },
  13452. enumerable: true,
  13453. configurable: true
  13454. });
  13455. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13456. get: function () {
  13457. var mousewheel = this.inputs.attached["mousewheel"];
  13458. if (mousewheel)
  13459. return mousewheel.wheelPrecision;
  13460. },
  13461. set: function (value) {
  13462. var mousewheel = this.inputs.attached["mousewheel"];
  13463. if (mousewheel)
  13464. mousewheel.wheelPrecision = value;
  13465. },
  13466. enumerable: true,
  13467. configurable: true
  13468. });
  13469. // Cache
  13470. ArcRotateCamera.prototype._initCache = function () {
  13471. _super.prototype._initCache.call(this);
  13472. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13473. this._cache.alpha = undefined;
  13474. this._cache.beta = undefined;
  13475. this._cache.radius = undefined;
  13476. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13477. };
  13478. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13479. if (!ignoreParentClass) {
  13480. _super.prototype._updateCache.call(this);
  13481. }
  13482. this._cache.target.copyFrom(this._getTargetPosition());
  13483. this._cache.alpha = this.alpha;
  13484. this._cache.beta = this.beta;
  13485. this._cache.radius = this.radius;
  13486. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13487. };
  13488. ArcRotateCamera.prototype._getTargetPosition = function () {
  13489. if (this.target.getAbsolutePosition) {
  13490. return this.target.getAbsolutePosition();
  13491. }
  13492. return this.target;
  13493. };
  13494. // Synchronized
  13495. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13496. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13497. return false;
  13498. return this._cache.target.equals(this.target)
  13499. && this._cache.alpha === this.alpha
  13500. && this._cache.beta === this.beta
  13501. && this._cache.radius === this.radius
  13502. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13503. };
  13504. // Methods
  13505. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13506. var _this = this;
  13507. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13508. this._useCtrlForPanning = useCtrlForPanning;
  13509. this.inputs.attachElement(element, noPreventDefault);
  13510. this._reset = function () {
  13511. _this.inertialAlphaOffset = 0;
  13512. _this.inertialBetaOffset = 0;
  13513. _this.inertialRadiusOffset = 0;
  13514. };
  13515. };
  13516. ArcRotateCamera.prototype.detachControl = function (element) {
  13517. this.inputs.detachElement(element);
  13518. if (this._reset) {
  13519. this._reset();
  13520. }
  13521. };
  13522. ArcRotateCamera.prototype._checkInputs = function () {
  13523. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13524. if (this._collisionTriggered) {
  13525. return;
  13526. }
  13527. this.inputs.checkInputs();
  13528. // Inertia
  13529. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13530. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13531. this.beta += this.inertialBetaOffset;
  13532. this.radius -= this.inertialRadiusOffset;
  13533. this.inertialAlphaOffset *= this.inertia;
  13534. this.inertialBetaOffset *= this.inertia;
  13535. this.inertialRadiusOffset *= this.inertia;
  13536. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13537. this.inertialAlphaOffset = 0;
  13538. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13539. this.inertialBetaOffset = 0;
  13540. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13541. this.inertialRadiusOffset = 0;
  13542. }
  13543. // Panning inertia
  13544. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13545. if (!this._localDirection) {
  13546. this._localDirection = BABYLON.Vector3.Zero();
  13547. this._transformedDirection = BABYLON.Vector3.Zero();
  13548. }
  13549. this.inertialPanningX *= this.inertia;
  13550. this.inertialPanningY *= this.inertia;
  13551. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13552. this.inertialPanningX = 0;
  13553. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13554. this.inertialPanningY = 0;
  13555. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13556. this._localDirection.multiplyInPlace(this.panningAxis);
  13557. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13558. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13559. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13560. if (!this.panningAxis.y) {
  13561. this._transformedDirection.y = 0;
  13562. }
  13563. this.target.addInPlace(this._transformedDirection);
  13564. }
  13565. // Limits
  13566. this._checkLimits();
  13567. _super.prototype._checkInputs.call(this);
  13568. };
  13569. ArcRotateCamera.prototype._checkLimits = function () {
  13570. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13571. if (this.allowUpsideDown && this.beta > Math.PI) {
  13572. this.beta = this.beta - (2 * Math.PI);
  13573. }
  13574. }
  13575. else {
  13576. if (this.beta < this.lowerBetaLimit) {
  13577. this.beta = this.lowerBetaLimit;
  13578. }
  13579. }
  13580. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13581. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13582. this.beta = this.beta + (2 * Math.PI);
  13583. }
  13584. }
  13585. else {
  13586. if (this.beta > this.upperBetaLimit) {
  13587. this.beta = this.upperBetaLimit;
  13588. }
  13589. }
  13590. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13591. this.alpha = this.lowerAlphaLimit;
  13592. }
  13593. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13594. this.alpha = this.upperAlphaLimit;
  13595. }
  13596. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13597. this.radius = this.lowerRadiusLimit;
  13598. }
  13599. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13600. this.radius = this.upperRadiusLimit;
  13601. }
  13602. };
  13603. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13604. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13605. this.radius = radiusv3.length();
  13606. // Alpha
  13607. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13608. if (radiusv3.z < 0) {
  13609. this.alpha = 2 * Math.PI - this.alpha;
  13610. }
  13611. // Beta
  13612. this.beta = Math.acos(radiusv3.y / this.radius);
  13613. this._checkLimits();
  13614. };
  13615. ArcRotateCamera.prototype.setPosition = function (position) {
  13616. if (this.position.equals(position)) {
  13617. return;
  13618. }
  13619. this.position = position;
  13620. this.rebuildAnglesAndRadius();
  13621. };
  13622. ArcRotateCamera.prototype.setTarget = function (target) {
  13623. if (this._getTargetPosition().equals(target)) {
  13624. return;
  13625. }
  13626. this.target = target;
  13627. this.rebuildAnglesAndRadius();
  13628. };
  13629. ArcRotateCamera.prototype._getViewMatrix = function () {
  13630. // Compute
  13631. var cosa = Math.cos(this.alpha);
  13632. var sina = Math.sin(this.alpha);
  13633. var cosb = Math.cos(this.beta);
  13634. var sinb = Math.sin(this.beta);
  13635. if (sinb === 0) {
  13636. sinb = 0.0001;
  13637. }
  13638. var target = this._getTargetPosition();
  13639. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13640. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13641. this._collider.radius = this.collisionRadius;
  13642. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13643. this._collisionTriggered = true;
  13644. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13645. }
  13646. else {
  13647. this.position.copyFrom(this._newPosition);
  13648. var up = this.upVector;
  13649. if (this.allowUpsideDown && this.beta < 0) {
  13650. up = up.clone();
  13651. up = up.negate();
  13652. }
  13653. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13654. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13655. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13656. }
  13657. return this._viewMatrix;
  13658. };
  13659. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13660. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13661. meshes = meshes || this.getScene().meshes;
  13662. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13663. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13664. this.radius = distance * this.zoomOnFactor;
  13665. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13666. };
  13667. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13668. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13669. var meshesOrMinMaxVector;
  13670. var distance;
  13671. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13672. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13673. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13674. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13675. }
  13676. else {
  13677. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13678. distance = meshesOrMinMaxVectorAndDistance.distance;
  13679. }
  13680. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13681. if (!doNotUpdateMaxZ) {
  13682. this.maxZ = distance * 2;
  13683. }
  13684. };
  13685. /**
  13686. * @override
  13687. * Override Camera.createRigCamera
  13688. */
  13689. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13690. switch (this.cameraRigMode) {
  13691. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13692. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13693. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13694. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13695. case BABYLON.Camera.RIG_MODE_VR:
  13696. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13697. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13698. rigCam._cameraRigParams = {};
  13699. return rigCam;
  13700. }
  13701. return null;
  13702. };
  13703. /**
  13704. * @override
  13705. * Override Camera._updateRigCameras
  13706. */
  13707. ArcRotateCamera.prototype._updateRigCameras = function () {
  13708. switch (this.cameraRigMode) {
  13709. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13710. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13711. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13712. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13713. case BABYLON.Camera.RIG_MODE_VR:
  13714. var camLeft = this._rigCameras[0];
  13715. var camRight = this._rigCameras[1];
  13716. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13717. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13718. camLeft.beta = camRight.beta = this.beta;
  13719. camLeft.radius = camRight.radius = this.radius;
  13720. break;
  13721. }
  13722. _super.prototype._updateRigCameras.call(this);
  13723. };
  13724. ArcRotateCamera.prototype.dispose = function () {
  13725. this.inputs.clear();
  13726. _super.prototype.dispose.call(this);
  13727. };
  13728. ArcRotateCamera.prototype.getTypeName = function () {
  13729. return "ArcRotateCamera";
  13730. };
  13731. __decorate([
  13732. BABYLON.serialize()
  13733. ], ArcRotateCamera.prototype, "alpha", void 0);
  13734. __decorate([
  13735. BABYLON.serialize()
  13736. ], ArcRotateCamera.prototype, "beta", void 0);
  13737. __decorate([
  13738. BABYLON.serialize()
  13739. ], ArcRotateCamera.prototype, "radius", void 0);
  13740. __decorate([
  13741. BABYLON.serializeAsVector3()
  13742. ], ArcRotateCamera.prototype, "target", void 0);
  13743. __decorate([
  13744. BABYLON.serialize()
  13745. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13746. __decorate([
  13747. BABYLON.serialize()
  13748. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13749. __decorate([
  13750. BABYLON.serialize()
  13751. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13752. __decorate([
  13753. BABYLON.serialize()
  13754. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13755. __decorate([
  13756. BABYLON.serialize()
  13757. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13758. __decorate([
  13759. BABYLON.serialize()
  13760. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13761. __decorate([
  13762. BABYLON.serialize()
  13763. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13764. __decorate([
  13765. BABYLON.serialize()
  13766. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13767. __decorate([
  13768. BABYLON.serialize()
  13769. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13770. __decorate([
  13771. BABYLON.serialize()
  13772. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13773. __decorate([
  13774. BABYLON.serialize()
  13775. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13776. __decorate([
  13777. BABYLON.serialize()
  13778. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13779. __decorate([
  13780. BABYLON.serialize()
  13781. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13782. return ArcRotateCamera;
  13783. })(BABYLON.TargetCamera);
  13784. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13785. })(BABYLON || (BABYLON = {}));
  13786. var BABYLON;
  13787. (function (BABYLON) {
  13788. var ArcRotateCameraInputsManager = (function (_super) {
  13789. __extends(ArcRotateCameraInputsManager, _super);
  13790. function ArcRotateCameraInputsManager(camera) {
  13791. _super.call(this, camera);
  13792. }
  13793. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13794. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13795. return this;
  13796. };
  13797. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13798. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13799. return this;
  13800. };
  13801. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13802. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13803. return this;
  13804. };
  13805. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13806. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13807. return this;
  13808. };
  13809. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13810. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13811. return this;
  13812. };
  13813. return ArcRotateCameraInputsManager;
  13814. })(BABYLON.CameraInputsManager);
  13815. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13816. })(BABYLON || (BABYLON = {}));
  13817. var BABYLON;
  13818. (function (BABYLON) {
  13819. var RenderingManager = (function () {
  13820. function RenderingManager(scene) {
  13821. this._renderingGroups = new Array();
  13822. this._scene = scene;
  13823. }
  13824. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13825. if (this._scene._activeParticleSystems.length === 0) {
  13826. return;
  13827. }
  13828. // Particles
  13829. var activeCamera = this._scene.activeCamera;
  13830. var beforeParticlesDate = BABYLON.Tools.Now;
  13831. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13832. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13833. if (particleSystem.renderingGroupId !== index) {
  13834. continue;
  13835. }
  13836. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13837. continue;
  13838. }
  13839. this._clearDepthBuffer();
  13840. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13841. this._scene._activeParticles += particleSystem.render();
  13842. }
  13843. }
  13844. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13845. };
  13846. RenderingManager.prototype._renderSprites = function (index) {
  13847. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13848. return;
  13849. }
  13850. // Sprites
  13851. var activeCamera = this._scene.activeCamera;
  13852. var beforeSpritessDate = BABYLON.Tools.Now;
  13853. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13854. var spriteManager = this._scene.spriteManagers[id];
  13855. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13856. this._clearDepthBuffer();
  13857. spriteManager.render();
  13858. }
  13859. }
  13860. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13861. };
  13862. RenderingManager.prototype._clearDepthBuffer = function () {
  13863. if (this._depthBufferAlreadyCleaned) {
  13864. return;
  13865. }
  13866. this._scene.getEngine().clear(0, false, true);
  13867. this._depthBufferAlreadyCleaned = true;
  13868. };
  13869. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13870. if (this._currentRenderSprites) {
  13871. this._renderSprites(this._currentIndex);
  13872. }
  13873. if (this._currentRenderParticles) {
  13874. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13875. }
  13876. };
  13877. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13878. this._currentActiveMeshes = activeMeshes;
  13879. this._currentRenderParticles = renderParticles;
  13880. this._currentRenderSprites = renderSprites;
  13881. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13882. this._depthBufferAlreadyCleaned = index == 0;
  13883. var renderingGroup = this._renderingGroups[index];
  13884. var needToStepBack = false;
  13885. this._currentIndex = index;
  13886. if (renderingGroup) {
  13887. this._clearDepthBuffer();
  13888. if (!renderingGroup.onBeforeTransparentRendering) {
  13889. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13890. }
  13891. if (!renderingGroup.render(customRenderFunction)) {
  13892. this._renderingGroups.splice(index, 1);
  13893. needToStepBack = true;
  13894. this._renderSpritesAndParticles();
  13895. }
  13896. }
  13897. else {
  13898. this._renderSpritesAndParticles();
  13899. }
  13900. if (needToStepBack) {
  13901. index--;
  13902. }
  13903. }
  13904. };
  13905. RenderingManager.prototype.reset = function () {
  13906. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13907. if (renderingGroup) {
  13908. renderingGroup.prepare();
  13909. }
  13910. });
  13911. };
  13912. RenderingManager.prototype.dispatch = function (subMesh) {
  13913. var mesh = subMesh.getMesh();
  13914. var renderingGroupId = mesh.renderingGroupId || 0;
  13915. if (!this._renderingGroups[renderingGroupId]) {
  13916. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13917. }
  13918. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13919. };
  13920. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13921. return RenderingManager;
  13922. })();
  13923. BABYLON.RenderingManager = RenderingManager;
  13924. })(BABYLON || (BABYLON = {}));
  13925. var BABYLON;
  13926. (function (BABYLON) {
  13927. var RenderingGroup = (function () {
  13928. function RenderingGroup(index, scene) {
  13929. this.index = index;
  13930. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13931. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13932. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13933. this._scene = scene;
  13934. }
  13935. RenderingGroup.prototype.render = function (customRenderFunction) {
  13936. if (customRenderFunction) {
  13937. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13938. return true;
  13939. }
  13940. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13941. if (this.onBeforeTransparentRendering) {
  13942. this.onBeforeTransparentRendering();
  13943. }
  13944. return false;
  13945. }
  13946. var engine = this._scene.getEngine();
  13947. // Opaque
  13948. var subIndex;
  13949. var submesh;
  13950. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13951. submesh = this._opaqueSubMeshes.data[subIndex];
  13952. submesh.render(false);
  13953. }
  13954. // Alpha test
  13955. engine.setAlphaTesting(true);
  13956. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13957. submesh = this._alphaTestSubMeshes.data[subIndex];
  13958. submesh.render(false);
  13959. }
  13960. engine.setAlphaTesting(false);
  13961. if (this.onBeforeTransparentRendering) {
  13962. this.onBeforeTransparentRendering();
  13963. }
  13964. // Transparent
  13965. if (this._transparentSubMeshes.length) {
  13966. // Sorting
  13967. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13968. submesh = this._transparentSubMeshes.data[subIndex];
  13969. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13970. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13971. }
  13972. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13973. sortedArray.sort(function (a, b) {
  13974. // Alpha index first
  13975. if (a._alphaIndex > b._alphaIndex) {
  13976. return 1;
  13977. }
  13978. if (a._alphaIndex < b._alphaIndex) {
  13979. return -1;
  13980. }
  13981. // Then distance to camera
  13982. if (a._distanceToCamera < b._distanceToCamera) {
  13983. return 1;
  13984. }
  13985. if (a._distanceToCamera > b._distanceToCamera) {
  13986. return -1;
  13987. }
  13988. return 0;
  13989. });
  13990. // Rendering
  13991. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13992. submesh = sortedArray[subIndex];
  13993. submesh.render(true);
  13994. }
  13995. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13996. }
  13997. return true;
  13998. };
  13999. RenderingGroup.prototype.prepare = function () {
  14000. this._opaqueSubMeshes.reset();
  14001. this._transparentSubMeshes.reset();
  14002. this._alphaTestSubMeshes.reset();
  14003. };
  14004. RenderingGroup.prototype.dispatch = function (subMesh) {
  14005. var material = subMesh.getMaterial();
  14006. var mesh = subMesh.getMesh();
  14007. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14008. this._transparentSubMeshes.push(subMesh);
  14009. }
  14010. else if (material.needAlphaTesting()) {
  14011. this._alphaTestSubMeshes.push(subMesh);
  14012. }
  14013. else {
  14014. this._opaqueSubMeshes.push(subMesh); // Opaque
  14015. }
  14016. };
  14017. return RenderingGroup;
  14018. })();
  14019. BABYLON.RenderingGroup = RenderingGroup;
  14020. })(BABYLON || (BABYLON = {}));
  14021. var BABYLON;
  14022. (function (BABYLON) {
  14023. var PointerEventTypes = (function () {
  14024. function PointerEventTypes() {
  14025. }
  14026. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14027. get: function () {
  14028. return PointerEventTypes._POINTERDOWN;
  14029. },
  14030. enumerable: true,
  14031. configurable: true
  14032. });
  14033. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14034. get: function () {
  14035. return PointerEventTypes._POINTERUP;
  14036. },
  14037. enumerable: true,
  14038. configurable: true
  14039. });
  14040. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14041. get: function () {
  14042. return PointerEventTypes._POINTERMOVE;
  14043. },
  14044. enumerable: true,
  14045. configurable: true
  14046. });
  14047. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14048. get: function () {
  14049. return PointerEventTypes._POINTERWHEEL;
  14050. },
  14051. enumerable: true,
  14052. configurable: true
  14053. });
  14054. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14055. get: function () {
  14056. return PointerEventTypes._POINTERPICK;
  14057. },
  14058. enumerable: true,
  14059. configurable: true
  14060. });
  14061. PointerEventTypes._POINTERDOWN = 0x01;
  14062. PointerEventTypes._POINTERUP = 0x02;
  14063. PointerEventTypes._POINTERMOVE = 0x04;
  14064. PointerEventTypes._POINTERWHEEL = 0x08;
  14065. PointerEventTypes._POINTERPICK = 0x10;
  14066. return PointerEventTypes;
  14067. })();
  14068. BABYLON.PointerEventTypes = PointerEventTypes;
  14069. /**
  14070. * This type contains all the data related to a pointer event in Babylon.js.
  14071. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The differents event types can be found in the PointerEventTypes class.
  14072. */
  14073. var PointerInfo = (function () {
  14074. function PointerInfo(type, event, pickInfo) {
  14075. this.type = type;
  14076. this.event = event;
  14077. this.pickInfo = pickInfo;
  14078. }
  14079. return PointerInfo;
  14080. })();
  14081. BABYLON.PointerInfo = PointerInfo;
  14082. /**
  14083. * Represents a scene to be rendered by the engine.
  14084. * @see http://doc.babylonjs.com/page.php?p=21911
  14085. */
  14086. var Scene = (function () {
  14087. /**
  14088. * @constructor
  14089. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14090. */
  14091. function Scene(engine) {
  14092. // Members
  14093. this.autoClear = true;
  14094. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14095. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14096. this.forceWireframe = false;
  14097. this.forcePointsCloud = false;
  14098. this.forceShowBoundingBoxes = false;
  14099. this.animationsEnabled = true;
  14100. this.constantlyUpdateMeshUnderPointer = false;
  14101. // Events
  14102. /**
  14103. * An event triggered when the scene is disposed.
  14104. * @type {BABYLON.Observable}
  14105. */
  14106. this.onDisposeObservable = new BABYLON.Observable();
  14107. /**
  14108. * An event triggered before rendering the scene
  14109. * @type {BABYLON.Observable}
  14110. */
  14111. this.onBeforeRenderObservable = new BABYLON.Observable();
  14112. /**
  14113. * An event triggered after rendering the scene
  14114. * @type {BABYLON.Observable}
  14115. */
  14116. this.onAfterRenderObservable = new BABYLON.Observable();
  14117. /**
  14118. * An event triggered when the scene is ready
  14119. * @type {BABYLON.Observable}
  14120. */
  14121. this.onReadyObservable = new BABYLON.Observable();
  14122. /**
  14123. * An event triggered before rendering a camera
  14124. * @type {BABYLON.Observable}
  14125. */
  14126. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14127. /**
  14128. * An event triggered after rendering a camera
  14129. * @type {BABYLON.Observable}
  14130. */
  14131. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14132. /**
  14133. * An event triggered when a camera is created
  14134. * @type {BABYLON.Observable}
  14135. */
  14136. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14137. /**
  14138. * An event triggered when a camera is removed
  14139. * @type {BABYLON.Observable}
  14140. */
  14141. this.onCameraRemovedObservable = new BABYLON.Observable();
  14142. /**
  14143. * An event triggered when a light is created
  14144. * @type {BABYLON.Observable}
  14145. */
  14146. this.onNewLightAddedObservable = new BABYLON.Observable();
  14147. /**
  14148. * An event triggered when a light is removed
  14149. * @type {BABYLON.Observable}
  14150. */
  14151. this.onLightRemovedObservable = new BABYLON.Observable();
  14152. /**
  14153. * An event triggered when a geometry is created
  14154. * @type {BABYLON.Observable}
  14155. */
  14156. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14157. /**
  14158. * An event triggered when a geometry is removed
  14159. * @type {BABYLON.Observable}
  14160. */
  14161. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14162. /**
  14163. * An event triggered when a mesh is created
  14164. * @type {BABYLON.Observable}
  14165. */
  14166. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14167. /**
  14168. * An event triggered when a mesh is removed
  14169. * @type {BABYLON.Observable}
  14170. */
  14171. this.onMeshRemovedObservable = new BABYLON.Observable();
  14172. // Animations
  14173. this.animations = [];
  14174. /**
  14175. * Observable event triggered each time an input event is received from the rendering canvas
  14176. */
  14177. this.onPointerObservable = new BABYLON.Observable();
  14178. 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
  14179. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14180. this._startingPointerTime = 0;
  14181. // Fog
  14182. /**
  14183. * is fog enabled on this scene.
  14184. * @type {boolean}
  14185. */
  14186. this.fogEnabled = true;
  14187. this.fogMode = Scene.FOGMODE_NONE;
  14188. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14189. this.fogDensity = 0.1;
  14190. this.fogStart = 0;
  14191. this.fogEnd = 1000.0;
  14192. // Lights
  14193. /**
  14194. * is shadow enabled on this scene.
  14195. * @type {boolean}
  14196. */
  14197. this.shadowsEnabled = true;
  14198. /**
  14199. * is light enabled on this scene.
  14200. * @type {boolean}
  14201. */
  14202. this.lightsEnabled = true;
  14203. /**
  14204. * All of the lights added to this scene.
  14205. * @see BABYLON.Light
  14206. * @type {BABYLON.Light[]}
  14207. */
  14208. this.lights = new Array();
  14209. // Cameras
  14210. /**
  14211. * All of the cameras added to this scene.
  14212. * @see BABYLON.Camera
  14213. * @type {BABYLON.Camera[]}
  14214. */
  14215. this.cameras = new Array();
  14216. this.activeCameras = new Array();
  14217. // Meshes
  14218. /**
  14219. * All of the (abstract) meshes added to this scene.
  14220. * @see BABYLON.AbstractMesh
  14221. * @type {BABYLON.AbstractMesh[]}
  14222. */
  14223. this.meshes = new Array();
  14224. // Geometries
  14225. this._geometries = new Array();
  14226. this.materials = new Array();
  14227. this.multiMaterials = new Array();
  14228. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14229. // Textures
  14230. this.texturesEnabled = true;
  14231. this.textures = new Array();
  14232. // Particles
  14233. this.particlesEnabled = true;
  14234. this.particleSystems = new Array();
  14235. // Sprites
  14236. this.spritesEnabled = true;
  14237. this.spriteManagers = new Array();
  14238. // Layers
  14239. this.layers = new Array();
  14240. // Skeletons
  14241. this.skeletonsEnabled = true;
  14242. this.skeletons = new Array();
  14243. // Lens flares
  14244. this.lensFlaresEnabled = true;
  14245. this.lensFlareSystems = new Array();
  14246. // Collisions
  14247. this.collisionsEnabled = true;
  14248. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14249. // Postprocesses
  14250. this.postProcessesEnabled = true;
  14251. // Customs render targets
  14252. this.renderTargetsEnabled = true;
  14253. this.dumpNextRenderTargets = false;
  14254. this.customRenderTargets = new Array();
  14255. // Imported meshes
  14256. this.importedMeshesFiles = new Array();
  14257. // Probes
  14258. this.probesEnabled = true;
  14259. this.reflectionProbes = new Array();
  14260. this._actionManagers = new Array();
  14261. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14262. // Procedural textures
  14263. this.proceduralTexturesEnabled = true;
  14264. this._proceduralTextures = new Array();
  14265. this.soundTracks = new Array();
  14266. this._audioEnabled = true;
  14267. this._headphone = false;
  14268. this._totalVertices = 0;
  14269. this._activeIndices = 0;
  14270. this._activeParticles = 0;
  14271. this._lastFrameDuration = 0;
  14272. this._evaluateActiveMeshesDuration = 0;
  14273. this._renderTargetsDuration = 0;
  14274. this._particlesDuration = 0;
  14275. this._renderDuration = 0;
  14276. this._spritesDuration = 0;
  14277. this._animationRatio = 0;
  14278. this._renderId = 0;
  14279. this._executeWhenReadyTimeoutId = -1;
  14280. this._intermediateRendering = false;
  14281. this._toBeDisposed = new BABYLON.SmartArray(256);
  14282. this._pendingData = []; //ANY
  14283. this._activeMeshes = new BABYLON.SmartArray(256);
  14284. this._processedMaterials = new BABYLON.SmartArray(256);
  14285. this._renderTargets = new BABYLON.SmartArray(256);
  14286. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14287. this._activeSkeletons = new BABYLON.SmartArray(32);
  14288. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14289. this._activeBones = 0;
  14290. this._activeAnimatables = new Array();
  14291. this._transformMatrix = BABYLON.Matrix.Zero();
  14292. this._edgesRenderers = new BABYLON.SmartArray(16);
  14293. this._uniqueIdCounter = 0;
  14294. this._engine = engine;
  14295. engine.scenes.push(this);
  14296. this._renderingManager = new BABYLON.RenderingManager(this);
  14297. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14298. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14299. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14300. if (BABYLON.OutlineRenderer) {
  14301. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14302. }
  14303. this.attachControl();
  14304. this._debugLayer = new BABYLON.DebugLayer(this);
  14305. if (BABYLON.SoundTrack) {
  14306. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14307. }
  14308. //simplification queue
  14309. if (BABYLON.SimplificationQueue) {
  14310. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14311. }
  14312. //collision coordinator initialization. For now legacy per default.
  14313. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14314. }
  14315. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14316. get: function () {
  14317. return Scene._FOGMODE_NONE;
  14318. },
  14319. enumerable: true,
  14320. configurable: true
  14321. });
  14322. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14323. get: function () {
  14324. return Scene._FOGMODE_EXP;
  14325. },
  14326. enumerable: true,
  14327. configurable: true
  14328. });
  14329. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14330. get: function () {
  14331. return Scene._FOGMODE_EXP2;
  14332. },
  14333. enumerable: true,
  14334. configurable: true
  14335. });
  14336. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14337. get: function () {
  14338. return Scene._FOGMODE_LINEAR;
  14339. },
  14340. enumerable: true,
  14341. configurable: true
  14342. });
  14343. Object.defineProperty(Scene.prototype, "onDispose", {
  14344. set: function (callback) {
  14345. if (this._onDisposeObserver) {
  14346. this.onDisposeObservable.remove(this._onDisposeObserver);
  14347. }
  14348. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14349. },
  14350. enumerable: true,
  14351. configurable: true
  14352. });
  14353. Object.defineProperty(Scene.prototype, "beforeRender", {
  14354. set: function (callback) {
  14355. if (this._onBeforeRenderObserver) {
  14356. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14357. }
  14358. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. Object.defineProperty(Scene.prototype, "afterRender", {
  14364. set: function (callback) {
  14365. if (this._onAfterRenderObserver) {
  14366. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14367. }
  14368. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14369. },
  14370. enumerable: true,
  14371. configurable: true
  14372. });
  14373. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14374. set: function (callback) {
  14375. if (this._onBeforeCameraRenderObserver) {
  14376. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14377. }
  14378. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14379. },
  14380. enumerable: true,
  14381. configurable: true
  14382. });
  14383. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14384. set: function (callback) {
  14385. if (this._onAfterCameraRenderObserver) {
  14386. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14387. }
  14388. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14389. },
  14390. enumerable: true,
  14391. configurable: true
  14392. });
  14393. Object.defineProperty(Scene.prototype, "debugLayer", {
  14394. // Properties
  14395. get: function () {
  14396. return this._debugLayer;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14402. get: function () {
  14403. return this._workerCollisions;
  14404. },
  14405. set: function (enabled) {
  14406. enabled = (enabled && !!Worker);
  14407. this._workerCollisions = enabled;
  14408. if (this.collisionCoordinator) {
  14409. this.collisionCoordinator.destroy();
  14410. }
  14411. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14412. this.collisionCoordinator.init(this);
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14418. get: function () {
  14419. return this._selectionOctree;
  14420. },
  14421. enumerable: true,
  14422. configurable: true
  14423. });
  14424. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14425. /**
  14426. * The mesh that is currently under the pointer.
  14427. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14428. */
  14429. get: function () {
  14430. return this._pointerOverMesh;
  14431. },
  14432. enumerable: true,
  14433. configurable: true
  14434. });
  14435. Object.defineProperty(Scene.prototype, "pointerX", {
  14436. /**
  14437. * Current on-screen X position of the pointer
  14438. * @return {number} X position of the pointer
  14439. */
  14440. get: function () {
  14441. return this._pointerX;
  14442. },
  14443. enumerable: true,
  14444. configurable: true
  14445. });
  14446. Object.defineProperty(Scene.prototype, "pointerY", {
  14447. /**
  14448. * Current on-screen Y position of the pointer
  14449. * @return {number} Y position of the pointer
  14450. */
  14451. get: function () {
  14452. return this._pointerY;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. Scene.prototype.getCachedMaterial = function () {
  14458. return this._cachedMaterial;
  14459. };
  14460. Scene.prototype.getBoundingBoxRenderer = function () {
  14461. return this._boundingBoxRenderer;
  14462. };
  14463. Scene.prototype.getOutlineRenderer = function () {
  14464. return this._outlineRenderer;
  14465. };
  14466. Scene.prototype.getEngine = function () {
  14467. return this._engine;
  14468. };
  14469. Scene.prototype.getTotalVertices = function () {
  14470. return this._totalVertices;
  14471. };
  14472. Scene.prototype.getActiveIndices = function () {
  14473. return this._activeIndices;
  14474. };
  14475. Scene.prototype.getActiveParticles = function () {
  14476. return this._activeParticles;
  14477. };
  14478. Scene.prototype.getActiveBones = function () {
  14479. return this._activeBones;
  14480. };
  14481. // Stats
  14482. Scene.prototype.getLastFrameDuration = function () {
  14483. return this._lastFrameDuration;
  14484. };
  14485. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14486. return this._evaluateActiveMeshesDuration;
  14487. };
  14488. Scene.prototype.getActiveMeshes = function () {
  14489. return this._activeMeshes;
  14490. };
  14491. Scene.prototype.getRenderTargetsDuration = function () {
  14492. return this._renderTargetsDuration;
  14493. };
  14494. Scene.prototype.getRenderDuration = function () {
  14495. return this._renderDuration;
  14496. };
  14497. Scene.prototype.getParticlesDuration = function () {
  14498. return this._particlesDuration;
  14499. };
  14500. Scene.prototype.getSpritesDuration = function () {
  14501. return this._spritesDuration;
  14502. };
  14503. Scene.prototype.getAnimationRatio = function () {
  14504. return this._animationRatio;
  14505. };
  14506. Scene.prototype.getRenderId = function () {
  14507. return this._renderId;
  14508. };
  14509. Scene.prototype.incrementRenderId = function () {
  14510. this._renderId++;
  14511. };
  14512. Scene.prototype._updatePointerPosition = function (evt) {
  14513. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14514. this._pointerX = evt.clientX - canvasRect.left;
  14515. this._pointerY = evt.clientY - canvasRect.top;
  14516. this._unTranslatedPointerX = this._pointerX;
  14517. this._unTranslatedPointerY = this._pointerY;
  14518. if (this.cameraToUseForPointers) {
  14519. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14520. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14521. }
  14522. };
  14523. // Pointers handling
  14524. /**
  14525. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14526. * @param attachUp defines if you want to attach events to pointerup
  14527. * @param attachDown defines if you want to attach events to pointerdown
  14528. * @param attachMove defines if you want to attach events to pointermove
  14529. */
  14530. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14531. var _this = this;
  14532. if (attachUp === void 0) { attachUp = true; }
  14533. if (attachDown === void 0) { attachDown = true; }
  14534. if (attachMove === void 0) { attachMove = true; }
  14535. var spritePredicate = function (sprite) {
  14536. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14537. };
  14538. this._onPointerMove = function (evt) {
  14539. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14540. return;
  14541. }
  14542. var canvas = _this._engine.getRenderingCanvas();
  14543. _this._updatePointerPosition(evt);
  14544. if (!_this.pointerMovePredicate) {
  14545. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14546. }
  14547. // Meshes
  14548. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14549. if (pickResult.hit && pickResult.pickedMesh) {
  14550. _this.setPointerOverSprite(null);
  14551. _this.setPointerOverMesh(pickResult.pickedMesh);
  14552. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14553. canvas.style.cursor = "pointer";
  14554. }
  14555. else {
  14556. canvas.style.cursor = "";
  14557. }
  14558. }
  14559. else {
  14560. _this.setPointerOverMesh(null);
  14561. // Sprites
  14562. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14563. if (pickResult.hit && pickResult.pickedSprite) {
  14564. canvas.style.cursor = "pointer";
  14565. _this.setPointerOverSprite(pickResult.pickedSprite);
  14566. }
  14567. else {
  14568. _this.setPointerOverSprite(null);
  14569. // Restore pointer
  14570. canvas.style.cursor = "";
  14571. }
  14572. }
  14573. if (_this.onPointerMove) {
  14574. _this.onPointerMove(evt, pickResult);
  14575. }
  14576. if (_this.onPointerObservable.hasObservers()) {
  14577. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14578. var pi = new PointerInfo(type, evt, pickResult);
  14579. _this.onPointerObservable.notifyObservers(pi, type);
  14580. }
  14581. };
  14582. this._onPointerDown = function (evt) {
  14583. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14584. return;
  14585. }
  14586. _this._updatePointerPosition(evt);
  14587. _this._startingPointerPosition.x = _this._pointerX;
  14588. _this._startingPointerPosition.y = _this._pointerY;
  14589. _this._startingPointerTime = new Date().getTime();
  14590. if (!_this.pointerDownPredicate) {
  14591. _this.pointerDownPredicate = function (mesh) {
  14592. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14593. };
  14594. }
  14595. // Meshes
  14596. _this._pickedDownMesh = null;
  14597. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14598. if (pickResult.hit && pickResult.pickedMesh) {
  14599. if (pickResult.pickedMesh.actionManager) {
  14600. _this._pickedDownMesh = pickResult.pickedMesh;
  14601. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14602. switch (evt.button) {
  14603. case 0:
  14604. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14605. break;
  14606. case 1:
  14607. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14608. break;
  14609. case 2:
  14610. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14611. break;
  14612. }
  14613. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14614. }
  14615. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14616. var that = _this;
  14617. window.setTimeout(function () {
  14618. 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);
  14619. if (pickResult.hit && pickResult.pickedMesh) {
  14620. if (pickResult.pickedMesh.actionManager) {
  14621. 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)) {
  14622. that._startingPointerTime = 0;
  14623. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14624. }
  14625. }
  14626. }
  14627. }, BABYLON.ActionManager.LongPressDelay);
  14628. }
  14629. }
  14630. }
  14631. if (_this.onPointerDown) {
  14632. _this.onPointerDown(evt, pickResult);
  14633. }
  14634. if (_this.onPointerObservable.hasObservers()) {
  14635. var type = PointerEventTypes.POINTERDOWN;
  14636. var pi = new PointerInfo(type, evt, pickResult);
  14637. _this.onPointerObservable.notifyObservers(pi, type);
  14638. }
  14639. // Sprites
  14640. _this._pickedDownSprite = null;
  14641. if (_this.spriteManagers.length > 0) {
  14642. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14643. if (pickResult.hit && pickResult.pickedSprite) {
  14644. if (pickResult.pickedSprite.actionManager) {
  14645. _this._pickedDownSprite = pickResult.pickedSprite;
  14646. switch (evt.button) {
  14647. case 0:
  14648. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14649. break;
  14650. case 1:
  14651. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14652. break;
  14653. case 2:
  14654. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14655. break;
  14656. }
  14657. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14658. }
  14659. }
  14660. }
  14661. };
  14662. this._onPointerUp = function (evt) {
  14663. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14664. return;
  14665. }
  14666. _this._updatePointerPosition(evt);
  14667. if (!_this.pointerUpPredicate) {
  14668. _this.pointerUpPredicate = function (mesh) {
  14669. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14670. };
  14671. }
  14672. // Meshes
  14673. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14674. if (pickResult.hit && pickResult.pickedMesh) {
  14675. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14676. if (_this.onPointerPick) {
  14677. _this.onPointerPick(evt, pickResult);
  14678. }
  14679. if (_this.onPointerObservable.hasObservers()) {
  14680. var type = PointerEventTypes.POINTERPICK;
  14681. var pi = new PointerInfo(type, evt, pickResult);
  14682. _this.onPointerObservable.notifyObservers(pi, type);
  14683. }
  14684. }
  14685. if (pickResult.pickedMesh.actionManager) {
  14686. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14687. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14688. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14689. }
  14690. }
  14691. }
  14692. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14693. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14694. }
  14695. if (_this.onPointerUp) {
  14696. _this.onPointerUp(evt, pickResult);
  14697. }
  14698. if (_this.onPointerObservable.hasObservers()) {
  14699. var type = PointerEventTypes.POINTERUP;
  14700. var pi = new PointerInfo(type, evt, pickResult);
  14701. _this.onPointerObservable.notifyObservers(pi, type);
  14702. }
  14703. _this._startingPointerTime = 0;
  14704. // Sprites
  14705. if (_this.spriteManagers.length > 0) {
  14706. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14707. if (pickResult.hit && pickResult.pickedSprite) {
  14708. if (pickResult.pickedSprite.actionManager) {
  14709. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14710. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14711. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14712. }
  14713. }
  14714. }
  14715. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14716. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14717. }
  14718. }
  14719. };
  14720. this._onKeyDown = function (evt) {
  14721. if (_this.actionManager) {
  14722. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14723. }
  14724. };
  14725. this._onKeyUp = function (evt) {
  14726. if (_this.actionManager) {
  14727. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14728. }
  14729. };
  14730. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14731. if (attachMove) {
  14732. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14733. // Wheel
  14734. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14735. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14736. }
  14737. if (attachDown) {
  14738. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14739. }
  14740. if (attachUp) {
  14741. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14742. }
  14743. BABYLON.Tools.RegisterTopRootEvents([
  14744. { name: "keydown", handler: this._onKeyDown },
  14745. { name: "keyup", handler: this._onKeyUp }
  14746. ]);
  14747. };
  14748. Scene.prototype.detachControl = function () {
  14749. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14750. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14751. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14752. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14753. // Wheel
  14754. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14755. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14756. BABYLON.Tools.UnregisterTopRootEvents([
  14757. { name: "keydown", handler: this._onKeyDown },
  14758. { name: "keyup", handler: this._onKeyUp }
  14759. ]);
  14760. };
  14761. // Ready
  14762. Scene.prototype.isReady = function () {
  14763. if (this._pendingData.length > 0) {
  14764. return false;
  14765. }
  14766. var index;
  14767. for (index = 0; index < this._geometries.length; index++) {
  14768. var geometry = this._geometries[index];
  14769. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14770. return false;
  14771. }
  14772. }
  14773. for (index = 0; index < this.meshes.length; index++) {
  14774. var mesh = this.meshes[index];
  14775. if (!mesh.isReady()) {
  14776. return false;
  14777. }
  14778. var mat = mesh.material;
  14779. if (mat) {
  14780. if (!mat.isReady(mesh)) {
  14781. return false;
  14782. }
  14783. }
  14784. }
  14785. return true;
  14786. };
  14787. Scene.prototype.resetCachedMaterial = function () {
  14788. this._cachedMaterial = null;
  14789. };
  14790. Scene.prototype.registerBeforeRender = function (func) {
  14791. this.onBeforeRenderObservable.add(func);
  14792. };
  14793. Scene.prototype.unregisterBeforeRender = function (func) {
  14794. this.onBeforeRenderObservable.removeCallback(func);
  14795. };
  14796. Scene.prototype.registerAfterRender = function (func) {
  14797. this.onAfterRenderObservable.add(func);
  14798. };
  14799. Scene.prototype.unregisterAfterRender = function (func) {
  14800. this.onAfterRenderObservable.removeCallback(func);
  14801. };
  14802. Scene.prototype._addPendingData = function (data) {
  14803. this._pendingData.push(data);
  14804. };
  14805. Scene.prototype._removePendingData = function (data) {
  14806. var index = this._pendingData.indexOf(data);
  14807. if (index !== -1) {
  14808. this._pendingData.splice(index, 1);
  14809. }
  14810. };
  14811. Scene.prototype.getWaitingItemsCount = function () {
  14812. return this._pendingData.length;
  14813. };
  14814. /**
  14815. * Registers a function to be executed when the scene is ready.
  14816. * @param {Function} func - the function to be executed.
  14817. */
  14818. Scene.prototype.executeWhenReady = function (func) {
  14819. var _this = this;
  14820. this.onReadyObservable.add(func);
  14821. if (this._executeWhenReadyTimeoutId !== -1) {
  14822. return;
  14823. }
  14824. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14825. _this._checkIsReady();
  14826. }, 150);
  14827. };
  14828. Scene.prototype._checkIsReady = function () {
  14829. var _this = this;
  14830. if (this.isReady()) {
  14831. this.onReadyObservable.notifyObservers(this);
  14832. this.onReadyObservable.clear();
  14833. this._executeWhenReadyTimeoutId = -1;
  14834. return;
  14835. }
  14836. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14837. _this._checkIsReady();
  14838. }, 150);
  14839. };
  14840. // Animations
  14841. /**
  14842. * Will start the animation sequence of a given target
  14843. * @param target - the target
  14844. * @param {number} from - from which frame should animation start
  14845. * @param {number} to - till which frame should animation run.
  14846. * @param {boolean} [loop] - should the animation loop
  14847. * @param {number} [speedRatio] - the speed in which to run the animation
  14848. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14849. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14850. * @return {BABYLON.Animatable} the animatable object created for this animation
  14851. * @see BABYLON.Animatable
  14852. * @see http://doc.babylonjs.com/page.php?p=22081
  14853. */
  14854. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14855. if (speedRatio === void 0) { speedRatio = 1.0; }
  14856. this.stopAnimation(target);
  14857. if (!animatable) {
  14858. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14859. }
  14860. // Local animations
  14861. if (target.animations) {
  14862. animatable.appendAnimations(target, target.animations);
  14863. }
  14864. // Children animations
  14865. if (target.getAnimatables) {
  14866. var animatables = target.getAnimatables();
  14867. for (var index = 0; index < animatables.length; index++) {
  14868. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14869. }
  14870. }
  14871. animatable.reset();
  14872. return animatable;
  14873. };
  14874. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14875. if (speedRatio === undefined) {
  14876. speedRatio = 1.0;
  14877. }
  14878. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14879. return animatable;
  14880. };
  14881. Scene.prototype.getAnimatableByTarget = function (target) {
  14882. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14883. if (this._activeAnimatables[index].target === target) {
  14884. return this._activeAnimatables[index];
  14885. }
  14886. }
  14887. return null;
  14888. };
  14889. Object.defineProperty(Scene.prototype, "Animatables", {
  14890. get: function () {
  14891. return this._activeAnimatables;
  14892. },
  14893. enumerable: true,
  14894. configurable: true
  14895. });
  14896. /**
  14897. * Will stop the animation of the given target
  14898. * @param target - the target
  14899. * @see beginAnimation
  14900. */
  14901. Scene.prototype.stopAnimation = function (target) {
  14902. var animatable = this.getAnimatableByTarget(target);
  14903. if (animatable) {
  14904. animatable.stop();
  14905. }
  14906. };
  14907. Scene.prototype._animate = function () {
  14908. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14909. return;
  14910. }
  14911. if (!this._animationStartDate) {
  14912. if (this._pendingData.length > 0) {
  14913. return;
  14914. }
  14915. this._animationStartDate = BABYLON.Tools.Now;
  14916. }
  14917. // Getting time
  14918. var now = BABYLON.Tools.Now;
  14919. var delay = now - this._animationStartDate;
  14920. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14921. this._activeAnimatables[index]._animate(delay);
  14922. }
  14923. };
  14924. // Matrix
  14925. Scene.prototype.getViewMatrix = function () {
  14926. return this._viewMatrix;
  14927. };
  14928. Scene.prototype.getProjectionMatrix = function () {
  14929. return this._projectionMatrix;
  14930. };
  14931. Scene.prototype.getTransformMatrix = function () {
  14932. return this._transformMatrix;
  14933. };
  14934. Scene.prototype.setTransformMatrix = function (view, projection) {
  14935. this._viewMatrix = view;
  14936. this._projectionMatrix = projection;
  14937. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14938. };
  14939. // Methods
  14940. Scene.prototype.addMesh = function (newMesh) {
  14941. newMesh.uniqueId = this._uniqueIdCounter++;
  14942. var position = this.meshes.push(newMesh);
  14943. //notify the collision coordinator
  14944. this.collisionCoordinator.onMeshAdded(newMesh);
  14945. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  14946. };
  14947. Scene.prototype.removeMesh = function (toRemove) {
  14948. var index = this.meshes.indexOf(toRemove);
  14949. if (index !== -1) {
  14950. // Remove from the scene if mesh found
  14951. this.meshes.splice(index, 1);
  14952. }
  14953. //notify the collision coordinator
  14954. this.collisionCoordinator.onMeshRemoved(toRemove);
  14955. this.onMeshRemovedObservable.notifyObservers(toRemove);
  14956. return index;
  14957. };
  14958. Scene.prototype.removeSkeleton = function (toRemove) {
  14959. var index = this.skeletons.indexOf(toRemove);
  14960. if (index !== -1) {
  14961. // Remove from the scene if mesh found
  14962. this.skeletons.splice(index, 1);
  14963. }
  14964. return index;
  14965. };
  14966. Scene.prototype.removeLight = function (toRemove) {
  14967. var index = this.lights.indexOf(toRemove);
  14968. if (index !== -1) {
  14969. // Remove from the scene if mesh found
  14970. this.lights.splice(index, 1);
  14971. }
  14972. this.onLightRemovedObservable.notifyObservers(toRemove);
  14973. return index;
  14974. };
  14975. Scene.prototype.removeCamera = function (toRemove) {
  14976. var index = this.cameras.indexOf(toRemove);
  14977. if (index !== -1) {
  14978. // Remove from the scene if mesh found
  14979. this.cameras.splice(index, 1);
  14980. }
  14981. // Remove from activeCameras
  14982. var index2 = this.activeCameras.indexOf(toRemove);
  14983. if (index2 !== -1) {
  14984. // Remove from the scene if mesh found
  14985. this.activeCameras.splice(index2, 1);
  14986. }
  14987. // Reset the activeCamera
  14988. if (this.activeCamera === toRemove) {
  14989. if (this.cameras.length > 0) {
  14990. this.activeCamera = this.cameras[0];
  14991. }
  14992. else {
  14993. this.activeCamera = null;
  14994. }
  14995. }
  14996. this.onCameraRemovedObservable.notifyObservers(toRemove);
  14997. return index;
  14998. };
  14999. Scene.prototype.addLight = function (newLight) {
  15000. newLight.uniqueId = this._uniqueIdCounter++;
  15001. var position = this.lights.push(newLight);
  15002. this.onNewLightAddedObservable.notifyObservers(newLight);
  15003. };
  15004. Scene.prototype.addCamera = function (newCamera) {
  15005. newCamera.uniqueId = this._uniqueIdCounter++;
  15006. var position = this.cameras.push(newCamera);
  15007. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15008. };
  15009. /**
  15010. * Switch active camera
  15011. * @param {Camera} newCamera - new active camera
  15012. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15013. */
  15014. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15015. if (attachControl === void 0) { attachControl = true; }
  15016. var canvas = this._engine.getRenderingCanvas();
  15017. this.activeCamera.detachControl(canvas);
  15018. this.activeCamera = newCamera;
  15019. if (attachControl) {
  15020. newCamera.attachControl(canvas);
  15021. }
  15022. };
  15023. /**
  15024. * sets the active camera of the scene using its ID
  15025. * @param {string} id - the camera's ID
  15026. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15027. * @see activeCamera
  15028. */
  15029. Scene.prototype.setActiveCameraByID = function (id) {
  15030. var camera = this.getCameraByID(id);
  15031. if (camera) {
  15032. this.activeCamera = camera;
  15033. return camera;
  15034. }
  15035. return null;
  15036. };
  15037. /**
  15038. * sets the active camera of the scene using its name
  15039. * @param {string} name - the camera's name
  15040. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15041. * @see activeCamera
  15042. */
  15043. Scene.prototype.setActiveCameraByName = function (name) {
  15044. var camera = this.getCameraByName(name);
  15045. if (camera) {
  15046. this.activeCamera = camera;
  15047. return camera;
  15048. }
  15049. return null;
  15050. };
  15051. /**
  15052. * get a material using its id
  15053. * @param {string} the material's ID
  15054. * @return {BABYLON.Material|null} the material or null if none found.
  15055. */
  15056. Scene.prototype.getMaterialByID = function (id) {
  15057. for (var index = 0; index < this.materials.length; index++) {
  15058. if (this.materials[index].id === id) {
  15059. return this.materials[index];
  15060. }
  15061. }
  15062. return null;
  15063. };
  15064. /**
  15065. * get a material using its name
  15066. * @param {string} the material's name
  15067. * @return {BABYLON.Material|null} the material or null if none found.
  15068. */
  15069. Scene.prototype.getMaterialByName = function (name) {
  15070. for (var index = 0; index < this.materials.length; index++) {
  15071. if (this.materials[index].name === name) {
  15072. return this.materials[index];
  15073. }
  15074. }
  15075. return null;
  15076. };
  15077. Scene.prototype.getLensFlareSystemByName = function (name) {
  15078. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15079. if (this.lensFlareSystems[index].name === name) {
  15080. return this.lensFlareSystems[index];
  15081. }
  15082. }
  15083. return null;
  15084. };
  15085. Scene.prototype.getLensFlareSystemByID = function (id) {
  15086. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15087. if (this.lensFlareSystems[index].id === id) {
  15088. return this.lensFlareSystems[index];
  15089. }
  15090. }
  15091. return null;
  15092. };
  15093. Scene.prototype.getCameraByID = function (id) {
  15094. for (var index = 0; index < this.cameras.length; index++) {
  15095. if (this.cameras[index].id === id) {
  15096. return this.cameras[index];
  15097. }
  15098. }
  15099. return null;
  15100. };
  15101. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15102. for (var index = 0; index < this.cameras.length; index++) {
  15103. if (this.cameras[index].uniqueId === uniqueId) {
  15104. return this.cameras[index];
  15105. }
  15106. }
  15107. return null;
  15108. };
  15109. /**
  15110. * get a camera using its name
  15111. * @param {string} the camera's name
  15112. * @return {BABYLON.Camera|null} the camera or null if none found.
  15113. */
  15114. Scene.prototype.getCameraByName = function (name) {
  15115. for (var index = 0; index < this.cameras.length; index++) {
  15116. if (this.cameras[index].name === name) {
  15117. return this.cameras[index];
  15118. }
  15119. }
  15120. return null;
  15121. };
  15122. /**
  15123. * get a bone using its id
  15124. * @param {string} the bone's id
  15125. * @return {BABYLON.Bone|null} the bone or null if not found
  15126. */
  15127. Scene.prototype.getBoneByID = function (id) {
  15128. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15129. var skeleton = this.skeletons[skeletonIndex];
  15130. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15131. if (skeleton.bones[boneIndex].id === id) {
  15132. return skeleton.bones[boneIndex];
  15133. }
  15134. }
  15135. }
  15136. return null;
  15137. };
  15138. /**
  15139. * get a bone using its id
  15140. * @param {string} the bone's name
  15141. * @return {BABYLON.Bone|null} the bone or null if not found
  15142. */
  15143. Scene.prototype.getBoneByName = function (name) {
  15144. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15145. var skeleton = this.skeletons[skeletonIndex];
  15146. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15147. if (skeleton.bones[boneIndex].name === name) {
  15148. return skeleton.bones[boneIndex];
  15149. }
  15150. }
  15151. }
  15152. return null;
  15153. };
  15154. /**
  15155. * get a light node using its name
  15156. * @param {string} the light's name
  15157. * @return {BABYLON.Light|null} the light or null if none found.
  15158. */
  15159. Scene.prototype.getLightByName = function (name) {
  15160. for (var index = 0; index < this.lights.length; index++) {
  15161. if (this.lights[index].name === name) {
  15162. return this.lights[index];
  15163. }
  15164. }
  15165. return null;
  15166. };
  15167. /**
  15168. * get a light node using its ID
  15169. * @param {string} the light's id
  15170. * @return {BABYLON.Light|null} the light or null if none found.
  15171. */
  15172. Scene.prototype.getLightByID = function (id) {
  15173. for (var index = 0; index < this.lights.length; index++) {
  15174. if (this.lights[index].id === id) {
  15175. return this.lights[index];
  15176. }
  15177. }
  15178. return null;
  15179. };
  15180. /**
  15181. * get a light node using its scene-generated unique ID
  15182. * @param {number} the light's unique id
  15183. * @return {BABYLON.Light|null} the light or null if none found.
  15184. */
  15185. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15186. for (var index = 0; index < this.lights.length; index++) {
  15187. if (this.lights[index].uniqueId === uniqueId) {
  15188. return this.lights[index];
  15189. }
  15190. }
  15191. return null;
  15192. };
  15193. /**
  15194. * get a particle system by id
  15195. * @param id {number} the particle system id
  15196. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15197. */
  15198. Scene.prototype.getParticleSystemByID = function (id) {
  15199. for (var index = 0; index < this.particleSystems.length; index++) {
  15200. if (this.particleSystems[index].id === id) {
  15201. return this.particleSystems[index];
  15202. }
  15203. }
  15204. return null;
  15205. };
  15206. /**
  15207. * get a geometry using its ID
  15208. * @param {string} the geometry's id
  15209. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15210. */
  15211. Scene.prototype.getGeometryByID = function (id) {
  15212. for (var index = 0; index < this._geometries.length; index++) {
  15213. if (this._geometries[index].id === id) {
  15214. return this._geometries[index];
  15215. }
  15216. }
  15217. return null;
  15218. };
  15219. /**
  15220. * add a new geometry to this scene.
  15221. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15222. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15223. * @return {boolean} was the geometry added or not
  15224. */
  15225. Scene.prototype.pushGeometry = function (geometry, force) {
  15226. if (!force && this.getGeometryByID(geometry.id)) {
  15227. return false;
  15228. }
  15229. this._geometries.push(geometry);
  15230. //notify the collision coordinator
  15231. this.collisionCoordinator.onGeometryAdded(geometry);
  15232. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15233. return true;
  15234. };
  15235. /**
  15236. * Removes an existing geometry
  15237. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15238. * @return {boolean} was the geometry removed or not
  15239. */
  15240. Scene.prototype.removeGeometry = function (geometry) {
  15241. var index = this._geometries.indexOf(geometry);
  15242. if (index > -1) {
  15243. this._geometries.splice(index, 1);
  15244. //notify the collision coordinator
  15245. this.collisionCoordinator.onGeometryDeleted(geometry);
  15246. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15247. return true;
  15248. }
  15249. return false;
  15250. };
  15251. Scene.prototype.getGeometries = function () {
  15252. return this._geometries;
  15253. };
  15254. /**
  15255. * Get the first added mesh found of a given ID
  15256. * @param {string} id - the id to search for
  15257. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15258. */
  15259. Scene.prototype.getMeshByID = function (id) {
  15260. for (var index = 0; index < this.meshes.length; index++) {
  15261. if (this.meshes[index].id === id) {
  15262. return this.meshes[index];
  15263. }
  15264. }
  15265. return null;
  15266. };
  15267. /**
  15268. * Get a mesh with its auto-generated unique id
  15269. * @param {number} uniqueId - the unique id to search for
  15270. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15271. */
  15272. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15273. for (var index = 0; index < this.meshes.length; index++) {
  15274. if (this.meshes[index].uniqueId === uniqueId) {
  15275. return this.meshes[index];
  15276. }
  15277. }
  15278. return null;
  15279. };
  15280. /**
  15281. * Get a the last added mesh found of a given ID
  15282. * @param {string} id - the id to search for
  15283. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15284. */
  15285. Scene.prototype.getLastMeshByID = function (id) {
  15286. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15287. if (this.meshes[index].id === id) {
  15288. return this.meshes[index];
  15289. }
  15290. }
  15291. return null;
  15292. };
  15293. /**
  15294. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15295. * @param {string} id - the id to search for
  15296. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15297. */
  15298. Scene.prototype.getLastEntryByID = function (id) {
  15299. var index;
  15300. for (index = this.meshes.length - 1; index >= 0; index--) {
  15301. if (this.meshes[index].id === id) {
  15302. return this.meshes[index];
  15303. }
  15304. }
  15305. for (index = this.cameras.length - 1; index >= 0; index--) {
  15306. if (this.cameras[index].id === id) {
  15307. return this.cameras[index];
  15308. }
  15309. }
  15310. for (index = this.lights.length - 1; index >= 0; index--) {
  15311. if (this.lights[index].id === id) {
  15312. return this.lights[index];
  15313. }
  15314. }
  15315. return null;
  15316. };
  15317. Scene.prototype.getNodeByID = function (id) {
  15318. var mesh = this.getMeshByID(id);
  15319. if (mesh) {
  15320. return mesh;
  15321. }
  15322. var light = this.getLightByID(id);
  15323. if (light) {
  15324. return light;
  15325. }
  15326. var camera = this.getCameraByID(id);
  15327. if (camera) {
  15328. return camera;
  15329. }
  15330. var bone = this.getBoneByID(id);
  15331. return bone;
  15332. };
  15333. Scene.prototype.getNodeByName = function (name) {
  15334. var mesh = this.getMeshByName(name);
  15335. if (mesh) {
  15336. return mesh;
  15337. }
  15338. var light = this.getLightByName(name);
  15339. if (light) {
  15340. return light;
  15341. }
  15342. var camera = this.getCameraByName(name);
  15343. if (camera) {
  15344. return camera;
  15345. }
  15346. var bone = this.getBoneByName(name);
  15347. return bone;
  15348. };
  15349. Scene.prototype.getMeshByName = function (name) {
  15350. for (var index = 0; index < this.meshes.length; index++) {
  15351. if (this.meshes[index].name === name) {
  15352. return this.meshes[index];
  15353. }
  15354. }
  15355. return null;
  15356. };
  15357. Scene.prototype.getSoundByName = function (name) {
  15358. var index;
  15359. if (BABYLON.AudioEngine) {
  15360. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15361. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15362. return this.mainSoundTrack.soundCollection[index];
  15363. }
  15364. }
  15365. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15366. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15367. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15368. return this.soundTracks[sdIndex].soundCollection[index];
  15369. }
  15370. }
  15371. }
  15372. }
  15373. return null;
  15374. };
  15375. Scene.prototype.getLastSkeletonByID = function (id) {
  15376. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15377. if (this.skeletons[index].id === id) {
  15378. return this.skeletons[index];
  15379. }
  15380. }
  15381. return null;
  15382. };
  15383. Scene.prototype.getSkeletonById = function (id) {
  15384. for (var index = 0; index < this.skeletons.length; index++) {
  15385. if (this.skeletons[index].id === id) {
  15386. return this.skeletons[index];
  15387. }
  15388. }
  15389. return null;
  15390. };
  15391. Scene.prototype.getSkeletonByName = function (name) {
  15392. for (var index = 0; index < this.skeletons.length; index++) {
  15393. if (this.skeletons[index].name === name) {
  15394. return this.skeletons[index];
  15395. }
  15396. }
  15397. return null;
  15398. };
  15399. Scene.prototype.isActiveMesh = function (mesh) {
  15400. return (this._activeMeshes.indexOf(mesh) !== -1);
  15401. };
  15402. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15403. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15404. var material = subMesh.getMaterial();
  15405. if (mesh.showSubMeshesBoundingBox) {
  15406. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15407. }
  15408. if (material) {
  15409. // Render targets
  15410. if (material.getRenderTargetTextures) {
  15411. if (this._processedMaterials.indexOf(material) === -1) {
  15412. this._processedMaterials.push(material);
  15413. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15414. }
  15415. }
  15416. // Dispatch
  15417. this._activeIndices += subMesh.indexCount;
  15418. this._renderingManager.dispatch(subMesh);
  15419. }
  15420. }
  15421. };
  15422. Scene.prototype._isInIntermediateRendering = function () {
  15423. return this._intermediateRendering;
  15424. };
  15425. Scene.prototype._evaluateActiveMeshes = function () {
  15426. this.activeCamera._activeMeshes.reset();
  15427. this._activeMeshes.reset();
  15428. this._renderingManager.reset();
  15429. this._processedMaterials.reset();
  15430. this._activeParticleSystems.reset();
  15431. this._activeSkeletons.reset();
  15432. this._softwareSkinnedMeshes.reset();
  15433. this._boundingBoxRenderer.reset();
  15434. this._edgesRenderers.reset();
  15435. if (!this._frustumPlanes) {
  15436. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15437. }
  15438. else {
  15439. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15440. }
  15441. // Meshes
  15442. var meshes;
  15443. var len;
  15444. if (this._selectionOctree) {
  15445. var selection = this._selectionOctree.select(this._frustumPlanes);
  15446. meshes = selection.data;
  15447. len = selection.length;
  15448. }
  15449. else {
  15450. len = this.meshes.length;
  15451. meshes = this.meshes;
  15452. }
  15453. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15454. var mesh = meshes[meshIndex];
  15455. if (mesh.isBlocked) {
  15456. continue;
  15457. }
  15458. this._totalVertices += mesh.getTotalVertices();
  15459. if (!mesh.isReady() || !mesh.isEnabled()) {
  15460. continue;
  15461. }
  15462. mesh.computeWorldMatrix();
  15463. // Intersections
  15464. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15465. this._meshesForIntersections.pushNoDuplicate(mesh);
  15466. }
  15467. // Switch to current LOD
  15468. var meshLOD = mesh.getLOD(this.activeCamera);
  15469. if (!meshLOD) {
  15470. continue;
  15471. }
  15472. mesh._preActivate();
  15473. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15474. this._activeMeshes.push(mesh);
  15475. this.activeCamera._activeMeshes.push(mesh);
  15476. mesh._activate(this._renderId);
  15477. this._activeMesh(meshLOD);
  15478. }
  15479. }
  15480. // Particle systems
  15481. var beforeParticlesDate = BABYLON.Tools.Now;
  15482. if (this.particlesEnabled) {
  15483. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15484. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15485. var particleSystem = this.particleSystems[particleIndex];
  15486. if (!particleSystem.isStarted()) {
  15487. continue;
  15488. }
  15489. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15490. this._activeParticleSystems.push(particleSystem);
  15491. particleSystem.animate();
  15492. }
  15493. }
  15494. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15495. }
  15496. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15497. };
  15498. Scene.prototype._activeMesh = function (mesh) {
  15499. if (mesh.skeleton && this.skeletonsEnabled) {
  15500. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15501. if (!mesh.computeBonesUsingShaders) {
  15502. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15503. }
  15504. }
  15505. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15506. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15507. }
  15508. if (mesh._edgesRenderer) {
  15509. this._edgesRenderers.push(mesh._edgesRenderer);
  15510. }
  15511. if (mesh && mesh.subMeshes) {
  15512. // Submeshes Octrees
  15513. var len;
  15514. var subMeshes;
  15515. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15516. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15517. len = intersections.length;
  15518. subMeshes = intersections.data;
  15519. }
  15520. else {
  15521. subMeshes = mesh.subMeshes;
  15522. len = subMeshes.length;
  15523. }
  15524. for (var subIndex = 0; subIndex < len; subIndex++) {
  15525. var subMesh = subMeshes[subIndex];
  15526. this._evaluateSubMesh(subMesh, mesh);
  15527. }
  15528. }
  15529. };
  15530. Scene.prototype.updateTransformMatrix = function (force) {
  15531. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15532. };
  15533. Scene.prototype._renderForCamera = function (camera) {
  15534. var engine = this._engine;
  15535. this.activeCamera = camera;
  15536. if (!this.activeCamera)
  15537. throw new Error("Active camera not set");
  15538. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15539. // Viewport
  15540. engine.setViewport(this.activeCamera.viewport);
  15541. // Camera
  15542. this.resetCachedMaterial();
  15543. this._renderId++;
  15544. this.updateTransformMatrix();
  15545. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15546. // Meshes
  15547. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15548. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15549. this._evaluateActiveMeshes();
  15550. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15551. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15552. // Skeletons
  15553. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15554. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15555. skeleton.prepare();
  15556. }
  15557. // Software skinning
  15558. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15559. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15560. mesh.applySkeleton(mesh.skeleton);
  15561. }
  15562. // Render targets
  15563. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15564. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15565. this._intermediateRendering = true;
  15566. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15567. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15568. var renderTarget = this._renderTargets.data[renderIndex];
  15569. if (renderTarget._shouldRender()) {
  15570. this._renderId++;
  15571. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15572. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15573. }
  15574. }
  15575. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15576. this._intermediateRendering = false;
  15577. this._renderId++;
  15578. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15579. }
  15580. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15581. // Prepare Frame
  15582. this.postProcessManager._prepareFrame();
  15583. var beforeRenderDate = BABYLON.Tools.Now;
  15584. // Backgrounds
  15585. var layerIndex;
  15586. var layer;
  15587. if (this.layers.length) {
  15588. engine.setDepthBuffer(false);
  15589. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15590. layer = this.layers[layerIndex];
  15591. if (layer.isBackground) {
  15592. layer.render();
  15593. }
  15594. }
  15595. engine.setDepthBuffer(true);
  15596. }
  15597. // Render
  15598. BABYLON.Tools.StartPerformanceCounter("Main render");
  15599. this._renderingManager.render(null, null, true, true);
  15600. BABYLON.Tools.EndPerformanceCounter("Main render");
  15601. // Bounding boxes
  15602. this._boundingBoxRenderer.render();
  15603. // Edges
  15604. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15605. this._edgesRenderers.data[edgesRendererIndex].render();
  15606. }
  15607. // Lens flares
  15608. if (this.lensFlaresEnabled) {
  15609. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15610. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15611. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15612. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15613. lensFlareSystem.render();
  15614. }
  15615. }
  15616. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15617. }
  15618. // Foregrounds
  15619. if (this.layers.length) {
  15620. engine.setDepthBuffer(false);
  15621. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15622. layer = this.layers[layerIndex];
  15623. if (!layer.isBackground) {
  15624. layer.render();
  15625. }
  15626. }
  15627. engine.setDepthBuffer(true);
  15628. }
  15629. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15630. // Finalize frame
  15631. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15632. // Update camera
  15633. this.activeCamera._updateFromScene();
  15634. // Reset some special arrays
  15635. this._renderTargets.reset();
  15636. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15637. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15638. };
  15639. Scene.prototype._processSubCameras = function (camera) {
  15640. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15641. this._renderForCamera(camera);
  15642. return;
  15643. }
  15644. // rig cameras
  15645. for (var index = 0; index < camera._rigCameras.length; index++) {
  15646. this._renderForCamera(camera._rigCameras[index]);
  15647. }
  15648. this.activeCamera = camera;
  15649. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15650. // Update camera
  15651. this.activeCamera._updateFromScene();
  15652. };
  15653. Scene.prototype._checkIntersections = function () {
  15654. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15655. var sourceMesh = this._meshesForIntersections.data[index];
  15656. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15657. var action = sourceMesh.actionManager.actions[actionIndex];
  15658. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15659. var parameters = action.getTriggerParameter();
  15660. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15661. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15662. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15663. if (areIntersecting && currentIntersectionInProgress === -1) {
  15664. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15665. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15666. sourceMesh._intersectionsInProgress.push(otherMesh);
  15667. }
  15668. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15669. sourceMesh._intersectionsInProgress.push(otherMesh);
  15670. }
  15671. }
  15672. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15673. //They intersected, and now they don't.
  15674. //is this trigger an exit trigger? execute an event.
  15675. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15676. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15677. }
  15678. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15679. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15680. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15681. }
  15682. }
  15683. }
  15684. }
  15685. }
  15686. };
  15687. Scene.prototype.render = function () {
  15688. var startDate = BABYLON.Tools.Now;
  15689. this._particlesDuration = 0;
  15690. this._spritesDuration = 0;
  15691. this._activeParticles = 0;
  15692. this._renderDuration = 0;
  15693. this._renderTargetsDuration = 0;
  15694. this._evaluateActiveMeshesDuration = 0;
  15695. this._totalVertices = 0;
  15696. this._activeIndices = 0;
  15697. this._activeBones = 0;
  15698. this.getEngine().resetDrawCalls();
  15699. this._meshesForIntersections.reset();
  15700. this.resetCachedMaterial();
  15701. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15702. // Actions
  15703. if (this.actionManager) {
  15704. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15705. }
  15706. //Simplification Queue
  15707. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15708. this.simplificationQueue.executeNext();
  15709. }
  15710. // Animations
  15711. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15712. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15713. this._animate();
  15714. // Physics
  15715. if (this._physicsEngine) {
  15716. BABYLON.Tools.StartPerformanceCounter("Physics");
  15717. this._physicsEngine._step(deltaTime / 1000.0);
  15718. BABYLON.Tools.EndPerformanceCounter("Physics");
  15719. }
  15720. // Before render
  15721. this.onBeforeRenderObservable.notifyObservers(this);
  15722. // Customs render targets
  15723. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15724. var engine = this.getEngine();
  15725. var currentActiveCamera = this.activeCamera;
  15726. if (this.renderTargetsEnabled) {
  15727. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15728. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15729. var renderTarget = this.customRenderTargets[customIndex];
  15730. if (renderTarget._shouldRender()) {
  15731. this._renderId++;
  15732. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15733. if (!this.activeCamera)
  15734. throw new Error("Active camera not set");
  15735. // Viewport
  15736. engine.setViewport(this.activeCamera.viewport);
  15737. // Camera
  15738. this.updateTransformMatrix();
  15739. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15740. }
  15741. }
  15742. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15743. this._renderId++;
  15744. }
  15745. if (this.customRenderTargets.length > 0) {
  15746. engine.restoreDefaultFramebuffer();
  15747. }
  15748. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15749. this.activeCamera = currentActiveCamera;
  15750. // Procedural textures
  15751. if (this.proceduralTexturesEnabled) {
  15752. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15753. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15754. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15755. if (proceduralTexture._shouldRender()) {
  15756. proceduralTexture.render();
  15757. }
  15758. }
  15759. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15760. }
  15761. // Clear
  15762. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15763. // Shadows
  15764. if (this.shadowsEnabled) {
  15765. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15766. var light = this.lights[lightIndex];
  15767. var shadowGenerator = light.getShadowGenerator();
  15768. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15769. this._renderTargets.push(shadowGenerator.getShadowMap());
  15770. }
  15771. }
  15772. }
  15773. // Depth renderer
  15774. if (this._depthRenderer) {
  15775. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15776. }
  15777. // RenderPipeline
  15778. this.postProcessRenderPipelineManager.update();
  15779. // Multi-cameras?
  15780. if (this.activeCameras.length > 0) {
  15781. var currentRenderId = this._renderId;
  15782. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15783. this._renderId = currentRenderId;
  15784. if (cameraIndex > 0) {
  15785. this._engine.clear(0, false, true);
  15786. }
  15787. this._processSubCameras(this.activeCameras[cameraIndex]);
  15788. }
  15789. }
  15790. else {
  15791. if (!this.activeCamera) {
  15792. throw new Error("No camera defined");
  15793. }
  15794. this._processSubCameras(this.activeCamera);
  15795. }
  15796. // Intersection checks
  15797. this._checkIntersections();
  15798. // Update the audio listener attached to the camera
  15799. if (BABYLON.AudioEngine) {
  15800. this._updateAudioParameters();
  15801. }
  15802. // After render
  15803. if (this.afterRender) {
  15804. this.afterRender();
  15805. }
  15806. this.onAfterRenderObservable.notifyObservers(this);
  15807. // Cleaning
  15808. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15809. this._toBeDisposed.data[index].dispose();
  15810. this._toBeDisposed[index] = null;
  15811. }
  15812. this._toBeDisposed.reset();
  15813. if (this.dumpNextRenderTargets) {
  15814. this.dumpNextRenderTargets = false;
  15815. }
  15816. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15817. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15818. };
  15819. Scene.prototype._updateAudioParameters = function () {
  15820. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15821. return;
  15822. }
  15823. var listeningCamera;
  15824. var audioEngine = BABYLON.Engine.audioEngine;
  15825. if (this.activeCameras.length > 0) {
  15826. listeningCamera = this.activeCameras[0];
  15827. }
  15828. else {
  15829. listeningCamera = this.activeCamera;
  15830. }
  15831. if (listeningCamera && audioEngine.canUseWebAudio) {
  15832. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15833. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15834. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15835. cameraDirection.normalize();
  15836. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15837. var i;
  15838. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15839. var sound = this.mainSoundTrack.soundCollection[i];
  15840. if (sound.useCustomAttenuation) {
  15841. sound.updateDistanceFromListener();
  15842. }
  15843. }
  15844. for (i = 0; i < this.soundTracks.length; i++) {
  15845. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15846. sound = this.soundTracks[i].soundCollection[j];
  15847. if (sound.useCustomAttenuation) {
  15848. sound.updateDistanceFromListener();
  15849. }
  15850. }
  15851. }
  15852. }
  15853. };
  15854. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15855. // Audio
  15856. get: function () {
  15857. return this._audioEnabled;
  15858. },
  15859. set: function (value) {
  15860. this._audioEnabled = value;
  15861. if (BABYLON.AudioEngine) {
  15862. if (this._audioEnabled) {
  15863. this._enableAudio();
  15864. }
  15865. else {
  15866. this._disableAudio();
  15867. }
  15868. }
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. Scene.prototype._disableAudio = function () {
  15874. var i;
  15875. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15876. this.mainSoundTrack.soundCollection[i].pause();
  15877. }
  15878. for (i = 0; i < this.soundTracks.length; i++) {
  15879. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15880. this.soundTracks[i].soundCollection[j].pause();
  15881. }
  15882. }
  15883. };
  15884. Scene.prototype._enableAudio = function () {
  15885. var i;
  15886. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15887. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15888. this.mainSoundTrack.soundCollection[i].play();
  15889. }
  15890. }
  15891. for (i = 0; i < this.soundTracks.length; i++) {
  15892. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15893. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15894. this.soundTracks[i].soundCollection[j].play();
  15895. }
  15896. }
  15897. }
  15898. };
  15899. Object.defineProperty(Scene.prototype, "headphone", {
  15900. get: function () {
  15901. return this._headphone;
  15902. },
  15903. set: function (value) {
  15904. this._headphone = value;
  15905. if (BABYLON.AudioEngine) {
  15906. if (this._headphone) {
  15907. this._switchAudioModeForHeadphones();
  15908. }
  15909. else {
  15910. this._switchAudioModeForNormalSpeakers();
  15911. }
  15912. }
  15913. },
  15914. enumerable: true,
  15915. configurable: true
  15916. });
  15917. Scene.prototype._switchAudioModeForHeadphones = function () {
  15918. this.mainSoundTrack.switchPanningModelToHRTF();
  15919. for (var i = 0; i < this.soundTracks.length; i++) {
  15920. this.soundTracks[i].switchPanningModelToHRTF();
  15921. }
  15922. };
  15923. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15924. this.mainSoundTrack.switchPanningModelToEqualPower();
  15925. for (var i = 0; i < this.soundTracks.length; i++) {
  15926. this.soundTracks[i].switchPanningModelToEqualPower();
  15927. }
  15928. };
  15929. Scene.prototype.enableDepthRenderer = function () {
  15930. if (this._depthRenderer) {
  15931. return this._depthRenderer;
  15932. }
  15933. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15934. return this._depthRenderer;
  15935. };
  15936. Scene.prototype.disableDepthRenderer = function () {
  15937. if (!this._depthRenderer) {
  15938. return;
  15939. }
  15940. this._depthRenderer.dispose();
  15941. this._depthRenderer = null;
  15942. };
  15943. Scene.prototype.freezeMaterials = function () {
  15944. for (var i = 0; i < this.materials.length; i++) {
  15945. this.materials[i].freeze();
  15946. }
  15947. };
  15948. Scene.prototype.unfreezeMaterials = function () {
  15949. for (var i = 0; i < this.materials.length; i++) {
  15950. this.materials[i].unfreeze();
  15951. }
  15952. };
  15953. Scene.prototype.dispose = function () {
  15954. this.beforeRender = null;
  15955. this.afterRender = null;
  15956. this.skeletons = [];
  15957. this._boundingBoxRenderer.dispose();
  15958. if (this._depthRenderer) {
  15959. this._depthRenderer.dispose();
  15960. }
  15961. // Debug layer
  15962. this.debugLayer.hide();
  15963. // Events
  15964. if (this.onDispose) {
  15965. this.onDispose();
  15966. }
  15967. this.onBeforeRenderObservable.clear();
  15968. this.onAfterRenderObservable.clear();
  15969. this.detachControl();
  15970. // Release sounds & sounds tracks
  15971. if (BABYLON.AudioEngine) {
  15972. this.disposeSounds();
  15973. }
  15974. // Detach cameras
  15975. var canvas = this._engine.getRenderingCanvas();
  15976. var index;
  15977. for (index = 0; index < this.cameras.length; index++) {
  15978. this.cameras[index].detachControl(canvas);
  15979. }
  15980. // Release lights
  15981. while (this.lights.length) {
  15982. this.lights[0].dispose();
  15983. }
  15984. // Release meshes
  15985. while (this.meshes.length) {
  15986. this.meshes[0].dispose(true);
  15987. }
  15988. // Release cameras
  15989. while (this.cameras.length) {
  15990. this.cameras[0].dispose();
  15991. }
  15992. // Release materials
  15993. while (this.materials.length) {
  15994. this.materials[0].dispose();
  15995. }
  15996. // Release particles
  15997. while (this.particleSystems.length) {
  15998. this.particleSystems[0].dispose();
  15999. }
  16000. // Release sprites
  16001. while (this.spriteManagers.length) {
  16002. this.spriteManagers[0].dispose();
  16003. }
  16004. // Release layers
  16005. while (this.layers.length) {
  16006. this.layers[0].dispose();
  16007. }
  16008. // Release textures
  16009. while (this.textures.length) {
  16010. this.textures[0].dispose();
  16011. }
  16012. // Post-processes
  16013. this.postProcessManager.dispose();
  16014. // Physics
  16015. if (this._physicsEngine) {
  16016. this.disablePhysicsEngine();
  16017. }
  16018. // Remove from engine
  16019. index = this._engine.scenes.indexOf(this);
  16020. if (index > -1) {
  16021. this._engine.scenes.splice(index, 1);
  16022. }
  16023. this._engine.wipeCaches();
  16024. };
  16025. // Release sounds & sounds tracks
  16026. Scene.prototype.disposeSounds = function () {
  16027. this.mainSoundTrack.dispose();
  16028. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16029. this.soundTracks[scIndex].dispose();
  16030. }
  16031. };
  16032. // Octrees
  16033. Scene.prototype.getWorldExtends = function () {
  16034. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16035. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16036. for (var index = 0; index < this.meshes.length; index++) {
  16037. var mesh = this.meshes[index];
  16038. mesh.computeWorldMatrix(true);
  16039. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16040. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16041. BABYLON.Tools.CheckExtends(minBox, min, max);
  16042. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16043. }
  16044. return {
  16045. min: min,
  16046. max: max
  16047. };
  16048. };
  16049. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16050. if (maxCapacity === void 0) { maxCapacity = 64; }
  16051. if (maxDepth === void 0) { maxDepth = 2; }
  16052. if (!this._selectionOctree) {
  16053. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16054. }
  16055. var worldExtends = this.getWorldExtends();
  16056. // Update octree
  16057. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16058. return this._selectionOctree;
  16059. };
  16060. // Picking
  16061. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16062. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16063. var engine = this._engine;
  16064. if (!camera) {
  16065. if (!this.activeCamera)
  16066. throw new Error("Active camera not set");
  16067. camera = this.activeCamera;
  16068. }
  16069. var cameraViewport = camera.viewport;
  16070. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16071. // Moving coordinates to local viewport world
  16072. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16073. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16074. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16075. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16076. };
  16077. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16078. var engine = this._engine;
  16079. if (!camera) {
  16080. if (!this.activeCamera)
  16081. throw new Error("Active camera not set");
  16082. camera = this.activeCamera;
  16083. }
  16084. var cameraViewport = camera.viewport;
  16085. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16086. var identity = BABYLON.Matrix.Identity();
  16087. // Moving coordinates to local viewport world
  16088. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16089. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16090. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16091. };
  16092. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16093. var pickingInfo = null;
  16094. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16095. var mesh = this.meshes[meshIndex];
  16096. if (predicate) {
  16097. if (!predicate(mesh)) {
  16098. continue;
  16099. }
  16100. }
  16101. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16102. continue;
  16103. }
  16104. var world = mesh.getWorldMatrix();
  16105. var ray = rayFunction(world);
  16106. var result = mesh.intersects(ray, fastCheck);
  16107. if (!result || !result.hit)
  16108. continue;
  16109. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16110. continue;
  16111. pickingInfo = result;
  16112. if (fastCheck) {
  16113. break;
  16114. }
  16115. }
  16116. return pickingInfo || new BABYLON.PickingInfo();
  16117. };
  16118. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16119. var pickingInfo = null;
  16120. camera = camera || this.activeCamera;
  16121. if (this.spriteManagers.length > 0) {
  16122. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16123. var spriteManager = this.spriteManagers[spriteIndex];
  16124. if (!spriteManager.isPickable) {
  16125. continue;
  16126. }
  16127. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16128. if (!result || !result.hit)
  16129. continue;
  16130. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16131. continue;
  16132. pickingInfo = result;
  16133. if (fastCheck) {
  16134. break;
  16135. }
  16136. }
  16137. }
  16138. return pickingInfo || new BABYLON.PickingInfo();
  16139. };
  16140. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16141. var _this = this;
  16142. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16143. /// <param name="x">X position on screen</param>
  16144. /// <param name="y">Y position on screen</param>
  16145. /// <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>
  16146. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16147. /// <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>
  16148. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16149. };
  16150. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16151. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16152. /// <param name="x">X position on screen</param>
  16153. /// <param name="y">Y position on screen</param>
  16154. /// <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>
  16155. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16156. /// <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>
  16157. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16158. };
  16159. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16160. var _this = this;
  16161. return this._internalPick(function (world) {
  16162. if (!_this._pickWithRayInverseMatrix) {
  16163. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16164. }
  16165. world.invertToRef(_this._pickWithRayInverseMatrix);
  16166. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16167. }, predicate, fastCheck);
  16168. };
  16169. Scene.prototype.setPointerOverMesh = function (mesh) {
  16170. if (this._pointerOverMesh === mesh) {
  16171. return;
  16172. }
  16173. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16174. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16175. }
  16176. this._pointerOverMesh = mesh;
  16177. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16178. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16179. }
  16180. };
  16181. Scene.prototype.getPointerOverMesh = function () {
  16182. return this._pointerOverMesh;
  16183. };
  16184. Scene.prototype.setPointerOverSprite = function (sprite) {
  16185. if (this._pointerOverSprite === sprite) {
  16186. return;
  16187. }
  16188. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16189. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16190. }
  16191. this._pointerOverSprite = sprite;
  16192. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16193. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16194. }
  16195. };
  16196. Scene.prototype.getPointerOverSprite = function () {
  16197. return this._pointerOverSprite;
  16198. };
  16199. // Physics
  16200. Scene.prototype.getPhysicsEngine = function () {
  16201. return this._physicsEngine;
  16202. };
  16203. /**
  16204. * Enables physics to the current scene
  16205. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16206. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16207. * @return {boolean} was the physics engine initialized
  16208. */
  16209. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16210. if (this._physicsEngine) {
  16211. return true;
  16212. }
  16213. try {
  16214. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16215. return true;
  16216. }
  16217. catch (e) {
  16218. BABYLON.Tools.Error(e.message);
  16219. return false;
  16220. }
  16221. };
  16222. Scene.prototype.disablePhysicsEngine = function () {
  16223. if (!this._physicsEngine) {
  16224. return;
  16225. }
  16226. this._physicsEngine.dispose();
  16227. this._physicsEngine = undefined;
  16228. };
  16229. Scene.prototype.isPhysicsEnabled = function () {
  16230. return this._physicsEngine !== undefined;
  16231. };
  16232. /**
  16233. *
  16234. * Sets the gravity of the physics engine (and NOT of the scene)
  16235. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16236. */
  16237. Scene.prototype.setGravity = function (gravity) {
  16238. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16239. if (!this._physicsEngine) {
  16240. return;
  16241. }
  16242. this._physicsEngine.setGravity(gravity);
  16243. };
  16244. /**
  16245. * Legacy support, using the new API
  16246. * @Deprecated
  16247. */
  16248. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16249. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16250. if (parts.parts) {
  16251. options = parts;
  16252. parts = parts.parts;
  16253. }
  16254. var mainMesh = parts[0].mesh;
  16255. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16256. for (var index = 1; index < parts.length; index++) {
  16257. var mesh = parts[index].mesh;
  16258. if (mesh.parent !== mainMesh) {
  16259. mesh.position = mesh.position.subtract(mainMesh.position);
  16260. mesh.parent = mainMesh;
  16261. }
  16262. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16263. }
  16264. mainMesh.physicsImpostor.forceUpdate();
  16265. };
  16266. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16267. var mesh = compound.parts[0].mesh;
  16268. mesh.physicsImpostor.dispose();
  16269. mesh.physicsImpostor = null;
  16270. };
  16271. // Misc.
  16272. Scene.prototype.createDefaultCameraOrLight = function () {
  16273. // Light
  16274. if (this.lights.length === 0) {
  16275. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16276. }
  16277. // Camera
  16278. if (!this.activeCamera) {
  16279. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16280. // Compute position
  16281. var worldExtends = this.getWorldExtends();
  16282. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16283. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16284. camera.setTarget(worldCenter);
  16285. this.activeCamera = camera;
  16286. }
  16287. };
  16288. // Tags
  16289. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16290. if (tagsQuery === undefined) {
  16291. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16292. return list;
  16293. }
  16294. var listByTags = [];
  16295. forEach = forEach || (function (item) { return; });
  16296. for (var i in list) {
  16297. var item = list[i];
  16298. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16299. listByTags.push(item);
  16300. forEach(item);
  16301. }
  16302. }
  16303. return listByTags;
  16304. };
  16305. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16306. return this._getByTags(this.meshes, tagsQuery, forEach);
  16307. };
  16308. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16309. return this._getByTags(this.cameras, tagsQuery, forEach);
  16310. };
  16311. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16312. return this._getByTags(this.lights, tagsQuery, forEach);
  16313. };
  16314. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16315. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16316. };
  16317. // Statics
  16318. Scene._FOGMODE_NONE = 0;
  16319. Scene._FOGMODE_EXP = 1;
  16320. Scene._FOGMODE_EXP2 = 2;
  16321. Scene._FOGMODE_LINEAR = 3;
  16322. Scene.MinDeltaTime = 1.0;
  16323. Scene.MaxDeltaTime = 1000.0;
  16324. return Scene;
  16325. })();
  16326. BABYLON.Scene = Scene;
  16327. })(BABYLON || (BABYLON = {}));
  16328. var BABYLON;
  16329. (function (BABYLON) {
  16330. var VertexBuffer = (function () {
  16331. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16332. if (engine instanceof BABYLON.Mesh) {
  16333. this._engine = engine.getScene().getEngine();
  16334. }
  16335. else {
  16336. this._engine = engine;
  16337. }
  16338. this._updatable = updatable;
  16339. this._data = data;
  16340. if (!postponeInternalCreation) {
  16341. this.create();
  16342. }
  16343. this._kind = kind;
  16344. if (stride) {
  16345. this._strideSize = stride;
  16346. return;
  16347. }
  16348. // Deduce stride from kind
  16349. switch (kind) {
  16350. case VertexBuffer.PositionKind:
  16351. this._strideSize = 3;
  16352. break;
  16353. case VertexBuffer.NormalKind:
  16354. this._strideSize = 3;
  16355. break;
  16356. case VertexBuffer.UVKind:
  16357. case VertexBuffer.UV2Kind:
  16358. case VertexBuffer.UV3Kind:
  16359. case VertexBuffer.UV4Kind:
  16360. case VertexBuffer.UV5Kind:
  16361. case VertexBuffer.UV6Kind:
  16362. this._strideSize = 2;
  16363. break;
  16364. case VertexBuffer.ColorKind:
  16365. this._strideSize = 4;
  16366. break;
  16367. case VertexBuffer.MatricesIndicesKind:
  16368. case VertexBuffer.MatricesIndicesExtraKind:
  16369. this._strideSize = 4;
  16370. break;
  16371. case VertexBuffer.MatricesWeightsKind:
  16372. case VertexBuffer.MatricesWeightsExtraKind:
  16373. this._strideSize = 4;
  16374. break;
  16375. }
  16376. }
  16377. // Properties
  16378. VertexBuffer.prototype.isUpdatable = function () {
  16379. return this._updatable;
  16380. };
  16381. VertexBuffer.prototype.getData = function () {
  16382. return this._data;
  16383. };
  16384. VertexBuffer.prototype.getBuffer = function () {
  16385. return this._buffer;
  16386. };
  16387. VertexBuffer.prototype.getStrideSize = function () {
  16388. return this._strideSize;
  16389. };
  16390. // Methods
  16391. VertexBuffer.prototype.create = function (data) {
  16392. if (!data && this._buffer) {
  16393. return; // nothing to do
  16394. }
  16395. data = data || this._data;
  16396. if (!this._buffer) {
  16397. if (this._updatable) {
  16398. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16399. }
  16400. else {
  16401. this._buffer = this._engine.createVertexBuffer(data);
  16402. }
  16403. }
  16404. if (this._updatable) {
  16405. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16406. this._data = data;
  16407. }
  16408. };
  16409. VertexBuffer.prototype.update = function (data) {
  16410. this.create(data);
  16411. };
  16412. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16413. if (!this._buffer) {
  16414. return;
  16415. }
  16416. if (this._updatable) {
  16417. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16418. this._data = null;
  16419. }
  16420. };
  16421. VertexBuffer.prototype.dispose = function () {
  16422. if (!this._buffer) {
  16423. return;
  16424. }
  16425. if (this._engine._releaseBuffer(this._buffer)) {
  16426. this._buffer = null;
  16427. }
  16428. };
  16429. Object.defineProperty(VertexBuffer, "PositionKind", {
  16430. get: function () {
  16431. return VertexBuffer._PositionKind;
  16432. },
  16433. enumerable: true,
  16434. configurable: true
  16435. });
  16436. Object.defineProperty(VertexBuffer, "NormalKind", {
  16437. get: function () {
  16438. return VertexBuffer._NormalKind;
  16439. },
  16440. enumerable: true,
  16441. configurable: true
  16442. });
  16443. Object.defineProperty(VertexBuffer, "UVKind", {
  16444. get: function () {
  16445. return VertexBuffer._UVKind;
  16446. },
  16447. enumerable: true,
  16448. configurable: true
  16449. });
  16450. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16451. get: function () {
  16452. return VertexBuffer._UV2Kind;
  16453. },
  16454. enumerable: true,
  16455. configurable: true
  16456. });
  16457. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16458. get: function () {
  16459. return VertexBuffer._UV3Kind;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16465. get: function () {
  16466. return VertexBuffer._UV4Kind;
  16467. },
  16468. enumerable: true,
  16469. configurable: true
  16470. });
  16471. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16472. get: function () {
  16473. return VertexBuffer._UV5Kind;
  16474. },
  16475. enumerable: true,
  16476. configurable: true
  16477. });
  16478. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16479. get: function () {
  16480. return VertexBuffer._UV6Kind;
  16481. },
  16482. enumerable: true,
  16483. configurable: true
  16484. });
  16485. Object.defineProperty(VertexBuffer, "ColorKind", {
  16486. get: function () {
  16487. return VertexBuffer._ColorKind;
  16488. },
  16489. enumerable: true,
  16490. configurable: true
  16491. });
  16492. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16493. get: function () {
  16494. return VertexBuffer._MatricesIndicesKind;
  16495. },
  16496. enumerable: true,
  16497. configurable: true
  16498. });
  16499. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16500. get: function () {
  16501. return VertexBuffer._MatricesWeightsKind;
  16502. },
  16503. enumerable: true,
  16504. configurable: true
  16505. });
  16506. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16507. get: function () {
  16508. return VertexBuffer._MatricesIndicesExtraKind;
  16509. },
  16510. enumerable: true,
  16511. configurable: true
  16512. });
  16513. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16514. get: function () {
  16515. return VertexBuffer._MatricesWeightsExtraKind;
  16516. },
  16517. enumerable: true,
  16518. configurable: true
  16519. });
  16520. // Enums
  16521. VertexBuffer._PositionKind = "position";
  16522. VertexBuffer._NormalKind = "normal";
  16523. VertexBuffer._UVKind = "uv";
  16524. VertexBuffer._UV2Kind = "uv2";
  16525. VertexBuffer._UV3Kind = "uv3";
  16526. VertexBuffer._UV4Kind = "uv4";
  16527. VertexBuffer._UV5Kind = "uv5";
  16528. VertexBuffer._UV6Kind = "uv6";
  16529. VertexBuffer._ColorKind = "color";
  16530. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16531. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16532. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16533. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16534. return VertexBuffer;
  16535. })();
  16536. BABYLON.VertexBuffer = VertexBuffer;
  16537. })(BABYLON || (BABYLON = {}));
  16538. var BABYLON;
  16539. (function (BABYLON) {
  16540. /**
  16541. * Creates an instance based on a source mesh.
  16542. */
  16543. var InstancedMesh = (function (_super) {
  16544. __extends(InstancedMesh, _super);
  16545. function InstancedMesh(name, source) {
  16546. _super.call(this, name, source.getScene());
  16547. source.instances.push(this);
  16548. this._sourceMesh = source;
  16549. this.position.copyFrom(source.position);
  16550. this.rotation.copyFrom(source.rotation);
  16551. this.scaling.copyFrom(source.scaling);
  16552. if (source.rotationQuaternion) {
  16553. this.rotationQuaternion = source.rotationQuaternion.clone();
  16554. }
  16555. this.infiniteDistance = source.infiniteDistance;
  16556. this.setPivotMatrix(source.getPivotMatrix());
  16557. this.refreshBoundingInfo();
  16558. this._syncSubMeshes();
  16559. }
  16560. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16561. // Methods
  16562. get: function () {
  16563. return this._sourceMesh.receiveShadows;
  16564. },
  16565. enumerable: true,
  16566. configurable: true
  16567. });
  16568. Object.defineProperty(InstancedMesh.prototype, "material", {
  16569. get: function () {
  16570. return this._sourceMesh.material;
  16571. },
  16572. enumerable: true,
  16573. configurable: true
  16574. });
  16575. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16576. get: function () {
  16577. return this._sourceMesh.visibility;
  16578. },
  16579. enumerable: true,
  16580. configurable: true
  16581. });
  16582. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16583. get: function () {
  16584. return this._sourceMesh.skeleton;
  16585. },
  16586. enumerable: true,
  16587. configurable: true
  16588. });
  16589. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16590. get: function () {
  16591. return this._sourceMesh.renderingGroupId;
  16592. },
  16593. enumerable: true,
  16594. configurable: true
  16595. });
  16596. InstancedMesh.prototype.getTotalVertices = function () {
  16597. return this._sourceMesh.getTotalVertices();
  16598. };
  16599. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16600. get: function () {
  16601. return this._sourceMesh;
  16602. },
  16603. enumerable: true,
  16604. configurable: true
  16605. });
  16606. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16607. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16608. };
  16609. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16610. return this._sourceMesh.isVerticesDataPresent(kind);
  16611. };
  16612. InstancedMesh.prototype.getIndices = function () {
  16613. return this._sourceMesh.getIndices();
  16614. };
  16615. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16616. get: function () {
  16617. return this._sourceMesh._positions;
  16618. },
  16619. enumerable: true,
  16620. configurable: true
  16621. });
  16622. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16623. var meshBB = this._sourceMesh.getBoundingInfo();
  16624. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16625. this._updateBoundingInfo();
  16626. };
  16627. InstancedMesh.prototype._preActivate = function () {
  16628. if (this._currentLOD) {
  16629. this._currentLOD._preActivate();
  16630. }
  16631. };
  16632. InstancedMesh.prototype._activate = function (renderId) {
  16633. if (this._currentLOD) {
  16634. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16635. }
  16636. };
  16637. InstancedMesh.prototype.getLOD = function (camera) {
  16638. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16639. if (this._currentLOD === this.sourceMesh) {
  16640. return this;
  16641. }
  16642. return this._currentLOD;
  16643. };
  16644. InstancedMesh.prototype._syncSubMeshes = function () {
  16645. this.releaseSubMeshes();
  16646. if (this._sourceMesh.subMeshes) {
  16647. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16648. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16649. }
  16650. }
  16651. };
  16652. InstancedMesh.prototype._generatePointsArray = function () {
  16653. return this._sourceMesh._generatePointsArray();
  16654. };
  16655. // Clone
  16656. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16657. var result = this._sourceMesh.createInstance(name);
  16658. // Deep copy
  16659. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16660. // Bounding info
  16661. this.refreshBoundingInfo();
  16662. // Parent
  16663. if (newParent) {
  16664. result.parent = newParent;
  16665. }
  16666. if (!doNotCloneChildren) {
  16667. // Children
  16668. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16669. var mesh = this.getScene().meshes[index];
  16670. if (mesh.parent === this) {
  16671. mesh.clone(mesh.name, result);
  16672. }
  16673. }
  16674. }
  16675. result.computeWorldMatrix(true);
  16676. return result;
  16677. };
  16678. // Dispoe
  16679. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16680. // Remove from mesh
  16681. var index = this._sourceMesh.instances.indexOf(this);
  16682. this._sourceMesh.instances.splice(index, 1);
  16683. _super.prototype.dispose.call(this, doNotRecurse);
  16684. };
  16685. return InstancedMesh;
  16686. })(BABYLON.AbstractMesh);
  16687. BABYLON.InstancedMesh = InstancedMesh;
  16688. })(BABYLON || (BABYLON = {}));
  16689. var BABYLON;
  16690. (function (BABYLON) {
  16691. var _InstancesBatch = (function () {
  16692. function _InstancesBatch() {
  16693. this.mustReturn = false;
  16694. this.visibleInstances = new Array();
  16695. this.renderSelf = new Array();
  16696. }
  16697. return _InstancesBatch;
  16698. })();
  16699. BABYLON._InstancesBatch = _InstancesBatch;
  16700. var Mesh = (function (_super) {
  16701. __extends(Mesh, _super);
  16702. /**
  16703. * @constructor
  16704. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16705. * @param {Scene} scene - The scene to add this mesh to.
  16706. * @param {Node} parent - The parent of this mesh, if it has one
  16707. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16708. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16709. * When false, achieved by calling a clone(), also passing False.
  16710. * This will make creation of children, recursive.
  16711. */
  16712. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16713. if (parent === void 0) { parent = null; }
  16714. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16715. _super.call(this, name, scene);
  16716. // Events
  16717. /**
  16718. * An event triggered before rendering the mesh
  16719. * @type {BABYLON.Observable}
  16720. */
  16721. this.onBeforeRenderObservable = new BABYLON.Observable();
  16722. /**
  16723. * An event triggered after rendering the mesh
  16724. * @type {BABYLON.Observable}
  16725. */
  16726. this.onAfterRenderObservable = new BABYLON.Observable();
  16727. /**
  16728. * An event triggered before drawing the mesh
  16729. * @type {BABYLON.Observable}
  16730. */
  16731. this.onBeforeDrawObservable = new BABYLON.Observable();
  16732. // Members
  16733. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16734. this.instances = new Array();
  16735. this._LODLevels = new Array();
  16736. this._visibleInstances = {};
  16737. this._renderIdForInstances = new Array();
  16738. this._batchCache = new _InstancesBatch();
  16739. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16740. this._sideOrientation = Mesh._DEFAULTSIDE;
  16741. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16742. if (source) {
  16743. // Geometry
  16744. if (source._geometry) {
  16745. source._geometry.applyToMesh(this);
  16746. }
  16747. // Deep copy
  16748. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16749. // Pivot
  16750. this.setPivotMatrix(source.getPivotMatrix());
  16751. this.id = name + "." + source.id;
  16752. // Material
  16753. this.material = source.material;
  16754. var index;
  16755. if (!doNotCloneChildren) {
  16756. // Children
  16757. for (index = 0; index < scene.meshes.length; index++) {
  16758. var mesh = scene.meshes[index];
  16759. if (mesh.parent === source) {
  16760. // doNotCloneChildren is always going to be False
  16761. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16762. }
  16763. }
  16764. }
  16765. // Physics clone
  16766. var physicsEngine = this.getScene().getPhysicsEngine();
  16767. if (clonePhysicsImpostor && physicsEngine) {
  16768. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16769. if (impostor) {
  16770. this.physicsImpostor = impostor.clone(this);
  16771. }
  16772. }
  16773. // Particles
  16774. for (index = 0; index < scene.particleSystems.length; index++) {
  16775. var system = scene.particleSystems[index];
  16776. if (system.emitter === source) {
  16777. system.clone(system.name, this);
  16778. }
  16779. }
  16780. this.computeWorldMatrix(true);
  16781. }
  16782. // Parent
  16783. if (parent !== null) {
  16784. this.parent = parent;
  16785. }
  16786. }
  16787. Object.defineProperty(Mesh, "FRONTSIDE", {
  16788. /**
  16789. * Mesh side orientation : usually the external or front surface
  16790. */
  16791. get: function () {
  16792. return Mesh._FRONTSIDE;
  16793. },
  16794. enumerable: true,
  16795. configurable: true
  16796. });
  16797. Object.defineProperty(Mesh, "BACKSIDE", {
  16798. /**
  16799. * Mesh side orientation : usually the internal or back surface
  16800. */
  16801. get: function () {
  16802. return Mesh._BACKSIDE;
  16803. },
  16804. enumerable: true,
  16805. configurable: true
  16806. });
  16807. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16808. /**
  16809. * Mesh side orientation : both internal and external or front and back surfaces
  16810. */
  16811. get: function () {
  16812. return Mesh._DOUBLESIDE;
  16813. },
  16814. enumerable: true,
  16815. configurable: true
  16816. });
  16817. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16818. /**
  16819. * Mesh side orientation : by default, `FRONTSIDE`
  16820. */
  16821. get: function () {
  16822. return Mesh._DEFAULTSIDE;
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. Object.defineProperty(Mesh, "NO_CAP", {
  16828. /**
  16829. * Mesh cap setting : no cap
  16830. */
  16831. get: function () {
  16832. return Mesh._NO_CAP;
  16833. },
  16834. enumerable: true,
  16835. configurable: true
  16836. });
  16837. Object.defineProperty(Mesh, "CAP_START", {
  16838. /**
  16839. * Mesh cap setting : one cap at the beginning of the mesh
  16840. */
  16841. get: function () {
  16842. return Mesh._CAP_START;
  16843. },
  16844. enumerable: true,
  16845. configurable: true
  16846. });
  16847. Object.defineProperty(Mesh, "CAP_END", {
  16848. /**
  16849. * Mesh cap setting : one cap at the end of the mesh
  16850. */
  16851. get: function () {
  16852. return Mesh._CAP_END;
  16853. },
  16854. enumerable: true,
  16855. configurable: true
  16856. });
  16857. Object.defineProperty(Mesh, "CAP_ALL", {
  16858. /**
  16859. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16860. */
  16861. get: function () {
  16862. return Mesh._CAP_ALL;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16868. set: function (callback) {
  16869. if (this._onBeforeDrawObserver) {
  16870. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16871. }
  16872. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16873. },
  16874. enumerable: true,
  16875. configurable: true
  16876. });
  16877. // Methods
  16878. /**
  16879. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16880. */
  16881. Mesh.prototype.toString = function (fullDetails) {
  16882. var ret = _super.prototype.toString.call(this, fullDetails);
  16883. ret += ", n vertices: " + this.getTotalVertices();
  16884. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16885. if (this.animations) {
  16886. for (var i = 0; i < this.animations.length; i++) {
  16887. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16888. }
  16889. }
  16890. if (fullDetails) {
  16891. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16892. }
  16893. return ret;
  16894. };
  16895. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16896. get: function () {
  16897. return this._LODLevels.length > 0;
  16898. },
  16899. enumerable: true,
  16900. configurable: true
  16901. });
  16902. Mesh.prototype._sortLODLevels = function () {
  16903. this._LODLevels.sort(function (a, b) {
  16904. if (a.distance < b.distance) {
  16905. return 1;
  16906. }
  16907. if (a.distance > b.distance) {
  16908. return -1;
  16909. }
  16910. return 0;
  16911. });
  16912. };
  16913. /**
  16914. * Add a mesh as LOD level triggered at the given distance.
  16915. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16916. * @param {number} distance - the distance from the center of the object to show this level
  16917. * @param {Mesh} mesh - the mesh to be added as LOD level
  16918. * @return {Mesh} this mesh (for chaining)
  16919. */
  16920. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16921. if (mesh && mesh._masterMesh) {
  16922. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16923. return this;
  16924. }
  16925. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16926. this._LODLevels.push(level);
  16927. if (mesh) {
  16928. mesh._masterMesh = this;
  16929. }
  16930. this._sortLODLevels();
  16931. return this;
  16932. };
  16933. /**
  16934. * Returns the LOD level mesh at the passed distance or null if not found.
  16935. * It is related to the method `addLODLevel(distance, mesh)`.
  16936. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16937. */
  16938. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16939. for (var index = 0; index < this._LODLevels.length; index++) {
  16940. var level = this._LODLevels[index];
  16941. if (level.distance === distance) {
  16942. return level.mesh;
  16943. }
  16944. }
  16945. return null;
  16946. };
  16947. /**
  16948. * Remove a mesh from the LOD array
  16949. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16950. * @param {Mesh} mesh - the mesh to be removed.
  16951. * @return {Mesh} this mesh (for chaining)
  16952. */
  16953. Mesh.prototype.removeLODLevel = function (mesh) {
  16954. for (var index = 0; index < this._LODLevels.length; index++) {
  16955. if (this._LODLevels[index].mesh === mesh) {
  16956. this._LODLevels.splice(index, 1);
  16957. if (mesh) {
  16958. mesh._masterMesh = null;
  16959. }
  16960. }
  16961. }
  16962. this._sortLODLevels();
  16963. return this;
  16964. };
  16965. /**
  16966. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  16967. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16968. */
  16969. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16970. if (!this._LODLevels || this._LODLevels.length === 0) {
  16971. return this;
  16972. }
  16973. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  16974. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16975. if (this.onLODLevelSelection) {
  16976. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16977. }
  16978. return this;
  16979. }
  16980. for (var index = 0; index < this._LODLevels.length; index++) {
  16981. var level = this._LODLevels[index];
  16982. if (level.distance < distanceToCamera) {
  16983. if (level.mesh) {
  16984. level.mesh._preActivate();
  16985. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16986. }
  16987. if (this.onLODLevelSelection) {
  16988. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16989. }
  16990. return level.mesh;
  16991. }
  16992. }
  16993. if (this.onLODLevelSelection) {
  16994. this.onLODLevelSelection(distanceToCamera, this, this);
  16995. }
  16996. return this;
  16997. };
  16998. Object.defineProperty(Mesh.prototype, "geometry", {
  16999. /**
  17000. * Returns the mesh internal `Geometry` object.
  17001. */
  17002. get: function () {
  17003. return this._geometry;
  17004. },
  17005. enumerable: true,
  17006. configurable: true
  17007. });
  17008. /**
  17009. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17010. */
  17011. Mesh.prototype.getTotalVertices = function () {
  17012. if (!this._geometry) {
  17013. return 0;
  17014. }
  17015. return this._geometry.getTotalVertices();
  17016. };
  17017. /**
  17018. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17019. * If `copywhenShared` is true (default false) and if the mesh has submeshes, the submesh data are duplicated in the returned array.
  17020. * Returns null if the mesh has no geometry or no vertex buffer.
  17021. * Possible `kind` values :
  17022. * - BABYLON.VertexBuffer.PositionKind
  17023. * - BABYLON.VertexBuffer.UVKind
  17024. * - BABYLON.VertexBuffer.UV2Kind
  17025. * - BABYLON.VertexBuffer.UV3Kind
  17026. * - BABYLON.VertexBuffer.UV4Kind
  17027. * - BABYLON.VertexBuffer.UV5Kind
  17028. * - BABYLON.VertexBuffer.UV6Kind
  17029. * - BABYLON.VertexBuffer.ColorKind
  17030. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17031. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17032. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17033. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17034. */
  17035. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17036. if (!this._geometry) {
  17037. return null;
  17038. }
  17039. return this._geometry.getVerticesData(kind, copyWhenShared);
  17040. };
  17041. /**
  17042. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17043. * Returns `undefined` if the mesh has no geometry.
  17044. * Possible `kind` values :
  17045. * - BABYLON.VertexBuffer.PositionKind
  17046. * - BABYLON.VertexBuffer.UVKind
  17047. * - BABYLON.VertexBuffer.UV2Kind
  17048. * - BABYLON.VertexBuffer.UV3Kind
  17049. * - BABYLON.VertexBuffer.UV4Kind
  17050. * - BABYLON.VertexBuffer.UV5Kind
  17051. * - BABYLON.VertexBuffer.UV6Kind
  17052. * - BABYLON.VertexBuffer.ColorKind
  17053. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17054. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17055. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17056. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17057. */
  17058. Mesh.prototype.getVertexBuffer = function (kind) {
  17059. if (!this._geometry) {
  17060. return undefined;
  17061. }
  17062. return this._geometry.getVertexBuffer(kind);
  17063. };
  17064. /**
  17065. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17066. * Possible `kind` values :
  17067. * - BABYLON.VertexBuffer.PositionKind
  17068. * - BABYLON.VertexBuffer.UVKind
  17069. * - BABYLON.VertexBuffer.UV2Kind
  17070. * - BABYLON.VertexBuffer.UV3Kind
  17071. * - BABYLON.VertexBuffer.UV4Kind
  17072. * - BABYLON.VertexBuffer.UV5Kind
  17073. * - BABYLON.VertexBuffer.UV6Kind
  17074. * - BABYLON.VertexBuffer.ColorKind
  17075. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17076. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17077. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17078. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17079. */
  17080. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17081. if (!this._geometry) {
  17082. if (this._delayInfo) {
  17083. return this._delayInfo.indexOf(kind) !== -1;
  17084. }
  17085. return false;
  17086. }
  17087. return this._geometry.isVerticesDataPresent(kind);
  17088. };
  17089. /**
  17090. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17091. * Possible `kind` values :
  17092. * - BABYLON.VertexBuffer.PositionKind
  17093. * - BABYLON.VertexBuffer.UVKind
  17094. * - BABYLON.VertexBuffer.UV2Kind
  17095. * - BABYLON.VertexBuffer.UV3Kind
  17096. * - BABYLON.VertexBuffer.UV4Kind
  17097. * - BABYLON.VertexBuffer.UV5Kind
  17098. * - BABYLON.VertexBuffer.UV6Kind
  17099. * - BABYLON.VertexBuffer.ColorKind
  17100. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17101. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17102. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17103. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17104. */
  17105. Mesh.prototype.getVerticesDataKinds = function () {
  17106. if (!this._geometry) {
  17107. var result = [];
  17108. if (this._delayInfo) {
  17109. for (var kind in this._delayInfo) {
  17110. result.push(kind);
  17111. }
  17112. }
  17113. return result;
  17114. }
  17115. return this._geometry.getVerticesDataKinds();
  17116. };
  17117. /**
  17118. * Returns a positive integer : the total number of indices in this mesh geometry.
  17119. * Returns zero if the mesh has no geometry.
  17120. */
  17121. Mesh.prototype.getTotalIndices = function () {
  17122. if (!this._geometry) {
  17123. return 0;
  17124. }
  17125. return this._geometry.getTotalIndices();
  17126. };
  17127. /**
  17128. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17129. * If the parameter `copyWhenShared` is true (default false) and if the mesh has submeshes, the submesh indices are duplicated in the returned array.
  17130. * Returns an empty array if the mesh has no geometry.
  17131. */
  17132. Mesh.prototype.getIndices = function (copyWhenShared) {
  17133. if (!this._geometry) {
  17134. return [];
  17135. }
  17136. return this._geometry.getIndices(copyWhenShared);
  17137. };
  17138. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17139. get: function () {
  17140. return this._masterMesh !== null && this._masterMesh !== undefined;
  17141. },
  17142. enumerable: true,
  17143. configurable: true
  17144. });
  17145. /**
  17146. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17147. */
  17148. Mesh.prototype.isReady = function () {
  17149. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17150. return false;
  17151. }
  17152. return _super.prototype.isReady.call(this);
  17153. };
  17154. /**
  17155. * Boolean : true if the mesh has been disposed.
  17156. */
  17157. Mesh.prototype.isDisposed = function () {
  17158. return this._isDisposed;
  17159. };
  17160. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17161. get: function () {
  17162. return this._sideOrientation;
  17163. },
  17164. /**
  17165. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17166. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17167. */
  17168. set: function (sideO) {
  17169. this._sideOrientation = sideO;
  17170. },
  17171. enumerable: true,
  17172. configurable: true
  17173. });
  17174. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17175. /**
  17176. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17177. * This property is pertinent only for updatable parametric shapes.
  17178. */
  17179. get: function () {
  17180. return this._areNormalsFrozen;
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. /**
  17186. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17187. * It has no effect at all on other shapes.
  17188. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17189. */
  17190. Mesh.prototype.freezeNormals = function () {
  17191. this._areNormalsFrozen = true;
  17192. };
  17193. /**
  17194. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17195. * It has no effect at all on other shapes.
  17196. * It reactivates the mesh normals computation if it was previously frozen.
  17197. */
  17198. Mesh.prototype.unfreezeNormals = function () {
  17199. this._areNormalsFrozen = false;
  17200. };
  17201. // Methods
  17202. Mesh.prototype._preActivate = function () {
  17203. var sceneRenderId = this.getScene().getRenderId();
  17204. if (this._preActivateId === sceneRenderId) {
  17205. return;
  17206. }
  17207. this._preActivateId = sceneRenderId;
  17208. this._visibleInstances = null;
  17209. };
  17210. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17211. if (this._visibleInstances) {
  17212. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17213. }
  17214. };
  17215. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17216. if (!this._visibleInstances) {
  17217. this._visibleInstances = {};
  17218. this._visibleInstances.defaultRenderId = renderId;
  17219. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17220. }
  17221. if (!this._visibleInstances[renderId]) {
  17222. this._visibleInstances[renderId] = new Array();
  17223. }
  17224. this._visibleInstances[renderId].push(instance);
  17225. };
  17226. /**
  17227. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17228. * This means the mesh underlying bounding box and shpere are recomputed.
  17229. */
  17230. Mesh.prototype.refreshBoundingInfo = function () {
  17231. if (this._boundingInfo.isLocked) {
  17232. return;
  17233. }
  17234. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17235. if (data) {
  17236. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17237. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17238. }
  17239. if (this.subMeshes) {
  17240. for (var index = 0; index < this.subMeshes.length; index++) {
  17241. this.subMeshes[index].refreshBoundingInfo();
  17242. }
  17243. }
  17244. this._updateBoundingInfo();
  17245. };
  17246. Mesh.prototype._createGlobalSubMesh = function () {
  17247. var totalVertices = this.getTotalVertices();
  17248. if (!totalVertices || !this.getIndices()) {
  17249. return null;
  17250. }
  17251. this.releaseSubMeshes();
  17252. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17253. };
  17254. Mesh.prototype.subdivide = function (count) {
  17255. if (count < 1) {
  17256. return;
  17257. }
  17258. var totalIndices = this.getTotalIndices();
  17259. var subdivisionSize = (totalIndices / count) | 0;
  17260. var offset = 0;
  17261. // Ensure that subdivisionSize is a multiple of 3
  17262. while (subdivisionSize % 3 !== 0) {
  17263. subdivisionSize++;
  17264. }
  17265. this.releaseSubMeshes();
  17266. for (var index = 0; index < count; index++) {
  17267. if (offset >= totalIndices) {
  17268. break;
  17269. }
  17270. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17271. offset += subdivisionSize;
  17272. }
  17273. this.synchronizeInstances();
  17274. };
  17275. /**
  17276. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17277. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17278. * The `data` are either a numeric array either a Float32Array.
  17279. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  17280. * Note that a new underlying `VertexBuffer` object is created each call.
  17281. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17282. * The same for the mesh submeshes if any.
  17283. *
  17284. * Possible `kind` values :
  17285. * - BABYLON.VertexBuffer.PositionKind
  17286. * - BABYLON.VertexBuffer.UVKind
  17287. * - BABYLON.VertexBuffer.UV2Kind
  17288. * - BABYLON.VertexBuffer.UV3Kind
  17289. * - BABYLON.VertexBuffer.UV4Kind
  17290. * - BABYLON.VertexBuffer.UV5Kind
  17291. * - BABYLON.VertexBuffer.UV6Kind
  17292. * - BABYLON.VertexBuffer.ColorKind
  17293. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17294. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17295. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17296. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17297. */
  17298. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17299. if (!this._geometry) {
  17300. var vertexData = new BABYLON.VertexData();
  17301. vertexData.set(data, kind);
  17302. var scene = this.getScene();
  17303. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17304. }
  17305. else {
  17306. this._geometry.setVerticesData(kind, data, updatable, stride);
  17307. }
  17308. };
  17309. /**
  17310. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17311. * If the mesh has no geometry, it is simply returned as it is.
  17312. * The `data` are either a numeric array either a Float32Array.
  17313. * No new underlying `VertexBuffer` object is created.
  17314. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17315. * The same for the mesh submeshes if any.
  17316. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17317. *
  17318. * Possible `kind` values :
  17319. * - BABYLON.VertexBuffer.PositionKind
  17320. * - BABYLON.VertexBuffer.UVKind
  17321. * - BABYLON.VertexBuffer.UV2Kind
  17322. * - BABYLON.VertexBuffer.UV3Kind
  17323. * - BABYLON.VertexBuffer.UV4Kind
  17324. * - BABYLON.VertexBuffer.UV5Kind
  17325. * - BABYLON.VertexBuffer.UV6Kind
  17326. * - BABYLON.VertexBuffer.ColorKind
  17327. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17328. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17329. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17330. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17331. */
  17332. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17333. if (!this._geometry) {
  17334. return;
  17335. }
  17336. if (!makeItUnique) {
  17337. this._geometry.updateVerticesData(kind, data, updateExtends);
  17338. }
  17339. else {
  17340. this.makeGeometryUnique();
  17341. this.updateVerticesData(kind, data, updateExtends, false);
  17342. }
  17343. };
  17344. /**
  17345. * Deprecated since BabylonJS v2.3
  17346. */
  17347. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17348. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17349. if (!this._geometry) {
  17350. return;
  17351. }
  17352. if (!makeItUnique) {
  17353. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17354. }
  17355. else {
  17356. this.makeGeometryUnique();
  17357. this.updateVerticesDataDirectly(kind, data, offset, false);
  17358. }
  17359. };
  17360. /**
  17361. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17362. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17363. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17364. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17365. */
  17366. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17367. if (computeNormals === void 0) { computeNormals = true; }
  17368. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17369. positionFunction(positions);
  17370. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17371. if (computeNormals) {
  17372. var indices = this.getIndices();
  17373. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17374. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17375. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17376. }
  17377. };
  17378. Mesh.prototype.makeGeometryUnique = function () {
  17379. if (!this._geometry) {
  17380. return;
  17381. }
  17382. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17383. geometry.applyToMesh(this);
  17384. };
  17385. /**
  17386. * Sets the mesh indices.
  17387. * Expects an array populated with integers or a Int32Array.
  17388. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17389. * This method creates a new index buffer each call.
  17390. */
  17391. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17392. if (!this._geometry) {
  17393. var vertexData = new BABYLON.VertexData();
  17394. vertexData.indices = indices;
  17395. var scene = this.getScene();
  17396. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17397. }
  17398. else {
  17399. this._geometry.setIndices(indices, totalVertices);
  17400. }
  17401. };
  17402. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17403. var engine = this.getScene().getEngine();
  17404. // Wireframe
  17405. var indexToBind;
  17406. if (this._unIndexed) {
  17407. indexToBind = null;
  17408. }
  17409. else {
  17410. switch (fillMode) {
  17411. case BABYLON.Material.PointFillMode:
  17412. indexToBind = null;
  17413. break;
  17414. case BABYLON.Material.WireFrameFillMode:
  17415. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17416. break;
  17417. default:
  17418. case BABYLON.Material.TriangleFillMode:
  17419. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17420. break;
  17421. }
  17422. }
  17423. // VBOs
  17424. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17425. };
  17426. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17427. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17428. return;
  17429. }
  17430. this.onBeforeDrawObservable.notifyObservers(this);
  17431. var engine = this.getScene().getEngine();
  17432. // Draw order
  17433. switch (fillMode) {
  17434. case BABYLON.Material.PointFillMode:
  17435. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17436. break;
  17437. case BABYLON.Material.WireFrameFillMode:
  17438. if (this._unIndexed) {
  17439. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17440. }
  17441. else {
  17442. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17443. }
  17444. break;
  17445. default:
  17446. if (this._unIndexed) {
  17447. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17448. }
  17449. else {
  17450. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17451. }
  17452. }
  17453. };
  17454. /**
  17455. * Registers a javascript function for this mesh that will be called just before the rendering process.
  17456. * This function is passed the current mesh and doesn't return anything.
  17457. */
  17458. Mesh.prototype.registerBeforeRender = function (func) {
  17459. this.onBeforeRenderObservable.add(func);
  17460. };
  17461. /**
  17462. * Disposes a previously registered javascript function called before the rendering.
  17463. * This function is passed the current mesh and doesn't return anything.
  17464. */
  17465. Mesh.prototype.unregisterBeforeRender = function (func) {
  17466. this.onBeforeRenderObservable.removeCallback(func);
  17467. };
  17468. /**
  17469. * Registers a javascript function for this mesh that will be called just after the rendering is complete.
  17470. * This function is passed the current mesh and doesn't return anything.
  17471. */
  17472. Mesh.prototype.registerAfterRender = function (func) {
  17473. this.onAfterRenderObservable.add(func);
  17474. };
  17475. /**
  17476. * Disposes a previously registered javascript function called after the rendering.
  17477. * This function is passed the current mesh and doesn't return anything.
  17478. */
  17479. Mesh.prototype.unregisterAfterRender = function (func) {
  17480. this.onAfterRenderObservable.removeCallback(func);
  17481. };
  17482. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17483. var scene = this.getScene();
  17484. this._batchCache.mustReturn = false;
  17485. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17486. this._batchCache.visibleInstances[subMeshId] = null;
  17487. if (this._visibleInstances) {
  17488. var currentRenderId = scene.getRenderId();
  17489. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17490. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17491. var selfRenderId = this._renderId;
  17492. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17493. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17494. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17495. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17496. }
  17497. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17498. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17499. this._batchCache.mustReturn = true;
  17500. return this._batchCache;
  17501. }
  17502. if (currentRenderId !== selfRenderId) {
  17503. this._batchCache.renderSelf[subMeshId] = false;
  17504. }
  17505. }
  17506. this._renderIdForInstances[subMeshId] = currentRenderId;
  17507. }
  17508. return this._batchCache;
  17509. };
  17510. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17511. var visibleInstances = batch.visibleInstances[subMesh._id];
  17512. var matricesCount = visibleInstances.length + 1;
  17513. var bufferSize = matricesCount * 16 * 4;
  17514. while (this._instancesBufferSize < bufferSize) {
  17515. this._instancesBufferSize *= 2;
  17516. }
  17517. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17518. if (this._worldMatricesInstancesBuffer) {
  17519. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17520. }
  17521. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17522. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17523. }
  17524. var offset = 0;
  17525. var instancesCount = 0;
  17526. var world = this.getWorldMatrix();
  17527. if (batch.renderSelf[subMesh._id]) {
  17528. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17529. offset += 16;
  17530. instancesCount++;
  17531. }
  17532. if (visibleInstances) {
  17533. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17534. var instance = visibleInstances[instanceIndex];
  17535. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17536. offset += 16;
  17537. instancesCount++;
  17538. }
  17539. }
  17540. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17541. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17542. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17543. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17544. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17545. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17546. this._draw(subMesh, fillMode, instancesCount);
  17547. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17548. };
  17549. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17550. var scene = this.getScene();
  17551. var engine = scene.getEngine();
  17552. if (hardwareInstancedRendering) {
  17553. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17554. }
  17555. else {
  17556. if (batch.renderSelf[subMesh._id]) {
  17557. // Draw
  17558. if (onBeforeDraw) {
  17559. onBeforeDraw(false, this.getWorldMatrix());
  17560. }
  17561. this._draw(subMesh, fillMode);
  17562. }
  17563. if (batch.visibleInstances[subMesh._id]) {
  17564. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17565. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17566. // World
  17567. var world = instance.getWorldMatrix();
  17568. if (onBeforeDraw) {
  17569. onBeforeDraw(true, world);
  17570. }
  17571. // Draw
  17572. this._draw(subMesh, fillMode);
  17573. }
  17574. }
  17575. }
  17576. };
  17577. /**
  17578. * Triggers the draw call for the mesh.
  17579. * You don't need to call this method by your own usually because the mesh rendering is handled by the scene rendering manager.
  17580. */
  17581. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17582. var scene = this.getScene();
  17583. // Managing instances
  17584. var batch = this._getInstancesRenderList(subMesh._id);
  17585. if (batch.mustReturn) {
  17586. return;
  17587. }
  17588. // Checking geometry state
  17589. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17590. return;
  17591. }
  17592. var callbackIndex;
  17593. this.onBeforeRenderObservable.notifyObservers(this);
  17594. var engine = scene.getEngine();
  17595. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17596. // Material
  17597. var effectiveMaterial = subMesh.getMaterial();
  17598. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17599. return;
  17600. }
  17601. // Outline - step 1
  17602. var savedDepthWrite = engine.getDepthWrite();
  17603. if (this.renderOutline) {
  17604. engine.setDepthWrite(false);
  17605. scene.getOutlineRenderer().render(subMesh, batch);
  17606. engine.setDepthWrite(savedDepthWrite);
  17607. }
  17608. effectiveMaterial._preBind();
  17609. var effect = effectiveMaterial.getEffect();
  17610. // Bind
  17611. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17612. this._bind(subMesh, effect, fillMode);
  17613. var world = this.getWorldMatrix();
  17614. effectiveMaterial.bind(world, this);
  17615. // Alpha mode
  17616. if (enableAlphaMode) {
  17617. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17618. }
  17619. // Draw
  17620. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17621. if (isInstance) {
  17622. effectiveMaterial.bindOnlyWorldMatrix(world);
  17623. }
  17624. });
  17625. // Unbind
  17626. effectiveMaterial.unbind();
  17627. // Outline - step 2
  17628. if (this.renderOutline && savedDepthWrite) {
  17629. engine.setDepthWrite(true);
  17630. engine.setColorWrite(false);
  17631. scene.getOutlineRenderer().render(subMesh, batch);
  17632. engine.setColorWrite(true);
  17633. }
  17634. // Overlay
  17635. if (this.renderOverlay) {
  17636. var currentMode = engine.getAlphaMode();
  17637. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17638. scene.getOutlineRenderer().render(subMesh, batch, true);
  17639. engine.setAlphaMode(currentMode);
  17640. }
  17641. this.onAfterRenderObservable.notifyObservers(this);
  17642. };
  17643. /**
  17644. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17645. */
  17646. Mesh.prototype.getEmittedParticleSystems = function () {
  17647. var results = new Array();
  17648. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17649. var particleSystem = this.getScene().particleSystems[index];
  17650. if (particleSystem.emitter === this) {
  17651. results.push(particleSystem);
  17652. }
  17653. }
  17654. return results;
  17655. };
  17656. /**
  17657. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17658. */
  17659. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17660. var results = new Array();
  17661. var descendants = this.getDescendants();
  17662. descendants.push(this);
  17663. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17664. var particleSystem = this.getScene().particleSystems[index];
  17665. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17666. results.push(particleSystem);
  17667. }
  17668. }
  17669. return results;
  17670. };
  17671. Mesh.prototype._checkDelayState = function () {
  17672. var _this = this;
  17673. var that = this;
  17674. var scene = this.getScene();
  17675. if (this._geometry) {
  17676. this._geometry.load(scene);
  17677. }
  17678. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17679. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17680. scene._addPendingData(that);
  17681. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17682. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17683. if (data instanceof ArrayBuffer) {
  17684. _this._delayLoadingFunction(data, _this);
  17685. }
  17686. else {
  17687. _this._delayLoadingFunction(JSON.parse(data), _this);
  17688. }
  17689. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17690. scene._removePendingData(_this);
  17691. }, function () { }, scene.database, getBinaryData);
  17692. }
  17693. };
  17694. /**
  17695. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17696. */
  17697. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17698. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17699. return false;
  17700. }
  17701. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17702. return false;
  17703. }
  17704. this._checkDelayState();
  17705. return true;
  17706. };
  17707. Mesh.prototype.setMaterialByID = function (id) {
  17708. var materials = this.getScene().materials;
  17709. var index;
  17710. for (index = 0; index < materials.length; index++) {
  17711. if (materials[index].id === id) {
  17712. this.material = materials[index];
  17713. return;
  17714. }
  17715. }
  17716. // Multi
  17717. var multiMaterials = this.getScene().multiMaterials;
  17718. for (index = 0; index < multiMaterials.length; index++) {
  17719. if (multiMaterials[index].id === id) {
  17720. this.material = multiMaterials[index];
  17721. return;
  17722. }
  17723. }
  17724. };
  17725. Mesh.prototype.getAnimatables = function () {
  17726. var results = [];
  17727. if (this.material) {
  17728. results.push(this.material);
  17729. }
  17730. if (this.skeleton) {
  17731. results.push(this.skeleton);
  17732. }
  17733. return results;
  17734. };
  17735. // Geometry
  17736. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17737. // Position
  17738. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17739. return;
  17740. }
  17741. this._resetPointsArrayCache();
  17742. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17743. var temp = [];
  17744. var index;
  17745. for (index = 0; index < data.length; index += 3) {
  17746. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17747. }
  17748. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17749. // Normals
  17750. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17751. return;
  17752. }
  17753. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17754. temp = [];
  17755. for (index = 0; index < data.length; index += 3) {
  17756. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17757. }
  17758. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17759. // flip faces?
  17760. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17761. this.flipFaces();
  17762. }
  17763. };
  17764. // Will apply current transform to mesh and reset world matrix
  17765. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17766. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17767. this.scaling.copyFromFloats(1, 1, 1);
  17768. this.position.copyFromFloats(0, 0, 0);
  17769. this.rotation.copyFromFloats(0, 0, 0);
  17770. //only if quaternion is already set
  17771. if (this.rotationQuaternion) {
  17772. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17773. }
  17774. this._worldMatrix = BABYLON.Matrix.Identity();
  17775. };
  17776. // Cache
  17777. Mesh.prototype._resetPointsArrayCache = function () {
  17778. this._positions = null;
  17779. };
  17780. Mesh.prototype._generatePointsArray = function () {
  17781. if (this._positions)
  17782. return true;
  17783. this._positions = [];
  17784. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17785. if (!data) {
  17786. return false;
  17787. }
  17788. for (var index = 0; index < data.length; index += 3) {
  17789. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17790. }
  17791. return true;
  17792. };
  17793. // Clone
  17794. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17795. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17796. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17797. };
  17798. // Dispose
  17799. Mesh.prototype.dispose = function (doNotRecurse) {
  17800. if (this._geometry) {
  17801. this._geometry.releaseForMesh(this, true);
  17802. }
  17803. // Instances
  17804. if (this._worldMatricesInstancesBuffer) {
  17805. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17806. this._worldMatricesInstancesBuffer = null;
  17807. }
  17808. while (this.instances.length) {
  17809. this.instances[0].dispose();
  17810. }
  17811. _super.prototype.dispose.call(this, doNotRecurse);
  17812. };
  17813. // Geometric tools
  17814. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17815. var _this = this;
  17816. var scene = this.getScene();
  17817. var onload = function (img) {
  17818. // Getting height map data
  17819. var canvas = document.createElement("canvas");
  17820. var context = canvas.getContext("2d");
  17821. var heightMapWidth = img.width;
  17822. var heightMapHeight = img.height;
  17823. canvas.width = heightMapWidth;
  17824. canvas.height = heightMapHeight;
  17825. context.drawImage(img, 0, 0);
  17826. // Create VertexData from map data
  17827. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17828. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17829. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17830. //execute success callback, if set
  17831. if (onSuccess) {
  17832. onSuccess(_this);
  17833. }
  17834. };
  17835. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17836. };
  17837. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17838. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17839. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17840. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17841. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17842. return;
  17843. }
  17844. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17845. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17846. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17847. var position = BABYLON.Vector3.Zero();
  17848. var normal = BABYLON.Vector3.Zero();
  17849. var uv = BABYLON.Vector2.Zero();
  17850. for (var index = 0; index < positions.length; index += 3) {
  17851. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17852. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17853. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17854. // Compute height
  17855. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17856. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17857. var pos = (u + v * heightMapWidth) * 4;
  17858. var r = buffer[pos] / 255.0;
  17859. var g = buffer[pos + 1] / 255.0;
  17860. var b = buffer[pos + 2] / 255.0;
  17861. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17862. normal.normalize();
  17863. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17864. position = position.add(normal);
  17865. position.toArray(positions, index);
  17866. }
  17867. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  17868. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  17869. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17870. };
  17871. /**
  17872. * Modify the mesh to get a flat shading rendering.
  17873. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  17874. * Warning : the mesh is really modified.
  17875. */
  17876. Mesh.prototype.convertToFlatShadedMesh = function () {
  17877. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  17878. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17879. var kinds = this.getVerticesDataKinds();
  17880. var vbs = [];
  17881. var data = [];
  17882. var newdata = [];
  17883. var updatableNormals = false;
  17884. var kindIndex;
  17885. var kind;
  17886. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17887. kind = kinds[kindIndex];
  17888. var vertexBuffer = this.getVertexBuffer(kind);
  17889. if (kind === BABYLON.VertexBuffer.NormalKind) {
  17890. updatableNormals = vertexBuffer.isUpdatable();
  17891. kinds.splice(kindIndex, 1);
  17892. kindIndex--;
  17893. continue;
  17894. }
  17895. vbs[kind] = vertexBuffer;
  17896. data[kind] = vbs[kind].getData();
  17897. newdata[kind] = [];
  17898. }
  17899. // Save previous submeshes
  17900. var previousSubmeshes = this.subMeshes.slice(0);
  17901. var indices = this.getIndices();
  17902. var totalIndices = this.getTotalIndices();
  17903. // Generating unique vertices per face
  17904. var index;
  17905. for (index = 0; index < totalIndices; index++) {
  17906. var vertexIndex = indices[index];
  17907. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17908. kind = kinds[kindIndex];
  17909. var stride = vbs[kind].getStrideSize();
  17910. for (var offset = 0; offset < stride; offset++) {
  17911. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17912. }
  17913. }
  17914. }
  17915. // Updating faces & normal
  17916. var normals = [];
  17917. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17918. for (index = 0; index < totalIndices; index += 3) {
  17919. indices[index] = index;
  17920. indices[index + 1] = index + 1;
  17921. indices[index + 2] = index + 2;
  17922. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17923. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17924. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17925. var p1p2 = p1.subtract(p2);
  17926. var p3p2 = p3.subtract(p2);
  17927. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17928. // Store same normals for every vertex
  17929. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17930. normals.push(normal.x);
  17931. normals.push(normal.y);
  17932. normals.push(normal.z);
  17933. }
  17934. }
  17935. this.setIndices(indices);
  17936. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17937. // Updating vertex buffers
  17938. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17939. kind = kinds[kindIndex];
  17940. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17941. }
  17942. // Updating submeshes
  17943. this.releaseSubMeshes();
  17944. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17945. var previousOne = previousSubmeshes[submeshIndex];
  17946. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17947. }
  17948. this.synchronizeInstances();
  17949. };
  17950. /**
  17951. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  17952. * In other words, more vertices, no more indices and a single bigger VBO.
  17953. */
  17954. Mesh.prototype.convertToUnIndexedMesh = function () {
  17955. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17956. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17957. var kinds = this.getVerticesDataKinds();
  17958. var vbs = [];
  17959. var data = [];
  17960. var newdata = [];
  17961. var updatableNormals = false;
  17962. var kindIndex;
  17963. var kind;
  17964. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17965. kind = kinds[kindIndex];
  17966. var vertexBuffer = this.getVertexBuffer(kind);
  17967. vbs[kind] = vertexBuffer;
  17968. data[kind] = vbs[kind].getData();
  17969. newdata[kind] = [];
  17970. }
  17971. // Save previous submeshes
  17972. var previousSubmeshes = this.subMeshes.slice(0);
  17973. var indices = this.getIndices();
  17974. var totalIndices = this.getTotalIndices();
  17975. // Generating unique vertices per face
  17976. var index;
  17977. for (index = 0; index < totalIndices; index++) {
  17978. var vertexIndex = indices[index];
  17979. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17980. kind = kinds[kindIndex];
  17981. var stride = vbs[kind].getStrideSize();
  17982. for (var offset = 0; offset < stride; offset++) {
  17983. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17984. }
  17985. }
  17986. }
  17987. // Updating indices
  17988. for (index = 0; index < totalIndices; index += 3) {
  17989. indices[index] = index;
  17990. indices[index + 1] = index + 1;
  17991. indices[index + 2] = index + 2;
  17992. }
  17993. this.setIndices(indices);
  17994. // Updating vertex buffers
  17995. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17996. kind = kinds[kindIndex];
  17997. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17998. }
  17999. // Updating submeshes
  18000. this.releaseSubMeshes();
  18001. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18002. var previousOne = previousSubmeshes[submeshIndex];
  18003. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18004. }
  18005. this._unIndexed = true;
  18006. this.synchronizeInstances();
  18007. };
  18008. /**
  18009. * Inverses facet orientations and inverts also the normals with `flipNormals` (default false) if true.
  18010. * Warning : the mesh is really modified.
  18011. */
  18012. Mesh.prototype.flipFaces = function (flipNormals) {
  18013. if (flipNormals === void 0) { flipNormals = false; }
  18014. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18015. var i;
  18016. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18017. for (i = 0; i < vertex_data.normals.length; i++) {
  18018. vertex_data.normals[i] *= -1;
  18019. }
  18020. }
  18021. var temp;
  18022. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18023. // reassign indices
  18024. temp = vertex_data.indices[i + 1];
  18025. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18026. vertex_data.indices[i + 2] = temp;
  18027. }
  18028. vertex_data.applyToMesh(this);
  18029. };
  18030. // Instances
  18031. /**
  18032. * Creates a new `InstancedMesh` object from the mesh model.
  18033. */
  18034. Mesh.prototype.createInstance = function (name) {
  18035. return new BABYLON.InstancedMesh(name, this);
  18036. };
  18037. Mesh.prototype.synchronizeInstances = function () {
  18038. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18039. var instance = this.instances[instanceIndex];
  18040. instance._syncSubMeshes();
  18041. }
  18042. };
  18043. /**
  18044. * Simplify the mesh according to the given array of settings.
  18045. * Function will return immediately and will simplify async.
  18046. * @param settings a collection of simplification settings.
  18047. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18048. * @param type the type of simplification to run.
  18049. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18050. */
  18051. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18052. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18053. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18054. this.getScene().simplificationQueue.addTask({
  18055. settings: settings,
  18056. parallelProcessing: parallelProcessing,
  18057. mesh: this,
  18058. simplificationType: simplificationType,
  18059. successCallback: successCallback
  18060. });
  18061. };
  18062. /**
  18063. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18064. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18065. * This should be used together with the simplification to avoid disappearing triangles.
  18066. * @param successCallback an optional success callback to be called after the optimization finished.
  18067. */
  18068. Mesh.prototype.optimizeIndices = function (successCallback) {
  18069. var _this = this;
  18070. var indices = this.getIndices();
  18071. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18072. var vectorPositions = [];
  18073. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18074. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18075. }
  18076. var dupes = [];
  18077. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18078. var realPos = vectorPositions.length - 1 - iteration;
  18079. var testedPosition = vectorPositions[realPos];
  18080. for (var j = 0; j < realPos; ++j) {
  18081. var againstPosition = vectorPositions[j];
  18082. if (testedPosition.equals(againstPosition)) {
  18083. dupes[realPos] = j;
  18084. break;
  18085. }
  18086. }
  18087. }, function () {
  18088. for (var i = 0; i < indices.length; ++i) {
  18089. indices[i] = dupes[indices[i]] || indices[i];
  18090. }
  18091. //indices are now reordered
  18092. var originalSubMeshes = _this.subMeshes.slice(0);
  18093. _this.setIndices(indices);
  18094. _this.subMeshes = originalSubMeshes;
  18095. if (successCallback) {
  18096. successCallback(_this);
  18097. }
  18098. });
  18099. };
  18100. // Statics
  18101. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18102. var mesh = new Mesh(parsedMesh.name, scene);
  18103. mesh.id = parsedMesh.id;
  18104. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18105. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18106. if (parsedMesh.rotationQuaternion) {
  18107. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18108. }
  18109. else if (parsedMesh.rotation) {
  18110. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18111. }
  18112. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18113. if (parsedMesh.localMatrix) {
  18114. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18115. }
  18116. else if (parsedMesh.pivotMatrix) {
  18117. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18118. }
  18119. mesh.setEnabled(parsedMesh.isEnabled);
  18120. mesh.isVisible = parsedMesh.isVisible;
  18121. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18122. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18123. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18124. if (parsedMesh.applyFog !== undefined) {
  18125. mesh.applyFog = parsedMesh.applyFog;
  18126. }
  18127. if (parsedMesh.pickable !== undefined) {
  18128. mesh.isPickable = parsedMesh.pickable;
  18129. }
  18130. if (parsedMesh.alphaIndex !== undefined) {
  18131. mesh.alphaIndex = parsedMesh.alphaIndex;
  18132. }
  18133. mesh.receiveShadows = parsedMesh.receiveShadows;
  18134. mesh.billboardMode = parsedMesh.billboardMode;
  18135. if (parsedMesh.visibility !== undefined) {
  18136. mesh.visibility = parsedMesh.visibility;
  18137. }
  18138. mesh.checkCollisions = parsedMesh.checkCollisions;
  18139. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18140. // freezeWorldMatrix
  18141. if (parsedMesh.freezeWorldMatrix) {
  18142. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18143. }
  18144. // Parent
  18145. if (parsedMesh.parentId) {
  18146. mesh._waitingParentId = parsedMesh.parentId;
  18147. }
  18148. // Actions
  18149. if (parsedMesh.actions !== undefined) {
  18150. mesh._waitingActions = parsedMesh.actions;
  18151. }
  18152. // Geometry
  18153. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18154. if (parsedMesh.delayLoadingFile) {
  18155. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18156. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18157. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18158. if (parsedMesh._binaryInfo) {
  18159. mesh._binaryInfo = parsedMesh._binaryInfo;
  18160. }
  18161. mesh._delayInfo = [];
  18162. if (parsedMesh.hasUVs) {
  18163. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18164. }
  18165. if (parsedMesh.hasUVs2) {
  18166. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18167. }
  18168. if (parsedMesh.hasUVs3) {
  18169. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18170. }
  18171. if (parsedMesh.hasUVs4) {
  18172. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18173. }
  18174. if (parsedMesh.hasUVs5) {
  18175. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18176. }
  18177. if (parsedMesh.hasUVs6) {
  18178. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18179. }
  18180. if (parsedMesh.hasColors) {
  18181. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18182. }
  18183. if (parsedMesh.hasMatricesIndices) {
  18184. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18185. }
  18186. if (parsedMesh.hasMatricesWeights) {
  18187. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18188. }
  18189. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18190. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18191. mesh._checkDelayState();
  18192. }
  18193. }
  18194. else {
  18195. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18196. }
  18197. // Material
  18198. if (parsedMesh.materialId) {
  18199. mesh.setMaterialByID(parsedMesh.materialId);
  18200. }
  18201. else {
  18202. mesh.material = null;
  18203. }
  18204. // Skeleton
  18205. if (parsedMesh.skeletonId > -1) {
  18206. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18207. if (parsedMesh.numBoneInfluencers) {
  18208. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18209. }
  18210. }
  18211. // Animations
  18212. if (parsedMesh.animations) {
  18213. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18214. var parsedAnimation = parsedMesh.animations[animationIndex];
  18215. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18216. }
  18217. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18218. }
  18219. if (parsedMesh.autoAnimate) {
  18220. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18221. }
  18222. // Layer Mask
  18223. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18224. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18225. }
  18226. else {
  18227. mesh.layerMask = 0x0FFFFFFF;
  18228. }
  18229. //(Deprecated) physics
  18230. if (parsedMesh.physicsImpostor) {
  18231. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18232. mass: parsedMesh.physicsMass,
  18233. friction: parsedMesh.physicsFriction,
  18234. restitution: parsedMesh.physicsRestitution
  18235. }, scene);
  18236. }
  18237. // Instances
  18238. if (parsedMesh.instances) {
  18239. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18240. var parsedInstance = parsedMesh.instances[index];
  18241. var instance = mesh.createInstance(parsedInstance.name);
  18242. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18243. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18244. if (parsedInstance.rotationQuaternion) {
  18245. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18246. }
  18247. else if (parsedInstance.rotation) {
  18248. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18249. }
  18250. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18251. instance.checkCollisions = mesh.checkCollisions;
  18252. if (parsedMesh.animations) {
  18253. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18254. parsedAnimation = parsedMesh.animations[animationIndex];
  18255. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18256. }
  18257. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18258. }
  18259. }
  18260. }
  18261. return mesh;
  18262. };
  18263. /**
  18264. * Creates a ribbon mesh.
  18265. * Please consider using the same method from the `MeshBuilder` class instead.
  18266. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18267. *
  18268. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18269. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18270. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18271. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18272. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  18273. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  18274. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  18275. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18276. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18278. */
  18279. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18280. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18281. pathArray: pathArray,
  18282. closeArray: closeArray,
  18283. closePath: closePath,
  18284. offset: offset,
  18285. updatable: updatable,
  18286. sideOrientation: sideOrientation,
  18287. instance: instance
  18288. }, scene);
  18289. };
  18290. /**
  18291. * Creates a plane polygonal mesh. By default, this is a disc.
  18292. * Please consider using the same method from the `MeshBuilder` class instead.
  18293. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18294. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  18295. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18296. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18297. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18298. */
  18299. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18300. var options = {
  18301. radius: radius,
  18302. tessellation: tessellation,
  18303. sideOrientation: sideOrientation,
  18304. updatable: updatable
  18305. };
  18306. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18307. };
  18308. /**
  18309. * Creates a box mesh.
  18310. * Please consider using the same method from the `MeshBuilder` class instead.
  18311. * The parameter `size` sets the size (float) of each box side (default 1).
  18312. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18314. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18315. */
  18316. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18317. var options = {
  18318. size: size,
  18319. sideOrientation: sideOrientation,
  18320. updatable: updatable
  18321. };
  18322. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18323. };
  18324. /**
  18325. * Creates a sphere mesh.
  18326. * Please consider using the same method from the `MeshBuilder` class instead.
  18327. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18328. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18330. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18332. */
  18333. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18334. var options = {
  18335. segments: segments,
  18336. diameterX: diameter,
  18337. diameterY: diameter,
  18338. diameterZ: diameter,
  18339. sideOrientation: sideOrientation,
  18340. updatable: updatable
  18341. };
  18342. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18343. };
  18344. /**
  18345. * Creates a cylinder or a cone mesh.
  18346. * Please consider using the same method from the `MeshBuilder` class instead.
  18347. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18348. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18349. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  18350. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18351. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18352. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18353. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18354. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18355. */
  18356. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18357. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18358. if (scene !== undefined) {
  18359. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18360. updatable = scene;
  18361. }
  18362. scene = subdivisions;
  18363. subdivisions = 1;
  18364. }
  18365. var options = {
  18366. height: height,
  18367. diameterTop: diameterTop,
  18368. diameterBottom: diameterBottom,
  18369. tessellation: tessellation,
  18370. subdivisions: subdivisions,
  18371. sideOrientation: sideOrientation,
  18372. updatable: updatable
  18373. };
  18374. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18375. };
  18376. // Torus (Code from SharpDX.org)
  18377. /**
  18378. * Creates a torus mesh.
  18379. * Please consider using the same method from the `MeshBuilder` class instead.
  18380. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18381. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18382. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18383. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18384. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18385. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18386. */
  18387. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18388. var options = {
  18389. diameter: diameter,
  18390. thickness: thickness,
  18391. tessellation: tessellation,
  18392. sideOrientation: sideOrientation,
  18393. updatable: updatable
  18394. };
  18395. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18396. };
  18397. /**
  18398. * Creates a torus knot mesh.
  18399. * Please consider using the same method from the `MeshBuilder` class instead.
  18400. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18401. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18402. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18403. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18404. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18405. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18406. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18407. */
  18408. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18409. var options = {
  18410. radius: radius,
  18411. tube: tube,
  18412. radialSegments: radialSegments,
  18413. tubularSegments: tubularSegments,
  18414. p: p,
  18415. q: q,
  18416. sideOrientation: sideOrientation,
  18417. updatable: updatable
  18418. };
  18419. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18420. };
  18421. /**
  18422. * Creates a line mesh.
  18423. * Please consider using the same method from the `MeshBuilder` class instead.
  18424. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18425. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18426. * The parameter `points` is an array successive Vector3.
  18427. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18428. * When updating an instance, remember that only point positions can change, not the number of points.
  18429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18430. */
  18431. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18432. var options = {
  18433. points: points,
  18434. updatable: updatable,
  18435. instance: instance
  18436. };
  18437. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18438. };
  18439. /**
  18440. * Creates a dashed line mesh.
  18441. * Please consider using the same method from the `MeshBuilder` class instead.
  18442. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  18443. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18444. * The parameter `points` is an array successive Vector3.
  18445. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18446. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18447. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18448. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  18449. * When updating an instance, remember that only point positions can change, not the number of points.
  18450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18451. */
  18452. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18453. var options = {
  18454. points: points,
  18455. dashSize: dashSize,
  18456. gapSize: gapSize,
  18457. dashNb: dashNb,
  18458. updatable: updatable
  18459. };
  18460. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18461. };
  18462. /**
  18463. * Creates an extruded shape mesh.
  18464. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18465. * Please consider using the same method from the `MeshBuilder` class instead.
  18466. *
  18467. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18468. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18469. * extruded along the Z axis.
  18470. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18471. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  18472. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18473. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18474. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18475. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18476. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18479. */
  18480. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18481. var options = {
  18482. shape: shape,
  18483. path: path,
  18484. scale: scale,
  18485. rotation: rotation,
  18486. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18487. sideOrientation: sideOrientation,
  18488. instance: instance,
  18489. updatable: updatable
  18490. };
  18491. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18492. };
  18493. /**
  18494. * Creates an custom extruded shape mesh.
  18495. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18496. * Please consider using the same method from the `MeshBuilder` class instead.
  18497. *
  18498. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18499. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18500. * extruded along the Z axis.
  18501. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18502. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18503. * and the distance of this point from the begining of the path :
  18504. * ```rotationFunction = function(i, distance) {
  18505. * // do things
  18506. * return rotationValue; }```
  18507. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18508. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  18509. * and the distance of this point from the begining of the path :
  18510. * ````scaleFunction = function(i, distance) {
  18511. * // do things
  18512. * return scaleValue;}```
  18513. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18514. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18515. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18516. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18517. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  18518. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18520. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18521. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18522. */
  18523. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18524. var options = {
  18525. shape: shape,
  18526. path: path,
  18527. scaleFunction: scaleFunction,
  18528. rotationFunction: rotationFunction,
  18529. ribbonCloseArray: ribbonCloseArray,
  18530. ribbonClosePath: ribbonClosePath,
  18531. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18532. sideOrientation: sideOrientation,
  18533. instance: instance,
  18534. updatable: updatable
  18535. };
  18536. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18537. };
  18538. /**
  18539. * Creates lathe mesh.
  18540. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18541. * Please consider using the same method from the `MeshBuilder` class instead.
  18542. *
  18543. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  18544. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18545. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18546. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18547. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18548. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18549. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18550. */
  18551. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18552. var options = {
  18553. shape: shape,
  18554. radius: radius,
  18555. tessellation: tessellation,
  18556. sideOrientation: sideOrientation,
  18557. updatable: updatable
  18558. };
  18559. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18560. };
  18561. /**
  18562. * Creates a plane mesh.
  18563. * Please consider using the same method from the `MeshBuilder` class instead.
  18564. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18565. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18566. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18567. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18568. */
  18569. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18570. var options = {
  18571. size: size,
  18572. width: size,
  18573. height: size,
  18574. sideOrientation: sideOrientation,
  18575. updatable: updatable
  18576. };
  18577. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18578. };
  18579. /**
  18580. * Creates a ground mesh.
  18581. * Please consider using the same method from the `MeshBuilder` class instead.
  18582. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18583. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18585. */
  18586. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18587. var options = {
  18588. width: width,
  18589. height: height,
  18590. subdivisions: subdivisions,
  18591. updatable: updatable
  18592. };
  18593. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18594. };
  18595. /**
  18596. * Creates a tiled ground mesh.
  18597. * Please consider using the same method from the `MeshBuilder` class instead.
  18598. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18599. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18600. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18601. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18602. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18603. * numbers of subdivisions on the ground width and height of each tile.
  18604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18605. */
  18606. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18607. var options = {
  18608. xmin: xmin,
  18609. zmin: zmin,
  18610. xmax: xmax,
  18611. zmax: zmax,
  18612. subdivisions: subdivisions,
  18613. precision: precision,
  18614. updatable: updatable
  18615. };
  18616. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18617. };
  18618. /**
  18619. * Creates a ground mesh from a height map.
  18620. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18621. * Please consider using the same method from the `MeshBuilder` class instead.
  18622. * The parameter `url` sets the URL of the height map image resource.
  18623. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18624. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18625. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18626. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18627. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  18628. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18629. * return; }```
  18630. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18631. */
  18632. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18633. var options = {
  18634. width: width,
  18635. height: height,
  18636. subdivisions: subdivisions,
  18637. minHeight: minHeight,
  18638. maxHeight: maxHeight,
  18639. updatable: updatable,
  18640. onReady: onReady
  18641. };
  18642. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18643. };
  18644. /**
  18645. * Creates a tube mesh.
  18646. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  18647. *
  18648. * Please consider using the same method from the `MeshBuilder` class instead.
  18649. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18650. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18651. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18652. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18653. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  18654. * It must return a radius value (positive float) :
  18655. * ```var radiusFunction = function(i, distance) {
  18656. * // do things
  18657. * return radius; }```
  18658. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  18659. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  18660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18661. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18663. */
  18664. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18665. var options = {
  18666. path: path,
  18667. radius: radius,
  18668. tessellation: tessellation,
  18669. radiusFunction: radiusFunction,
  18670. arc: 1,
  18671. cap: cap,
  18672. updatable: updatable,
  18673. sideOrientation: sideOrientation,
  18674. instance: instance
  18675. };
  18676. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18677. };
  18678. /**
  18679. * Creates a polyhedron mesh.
  18680. *
  18681. * Please consider using the same method from the `MeshBuilder` class instead.
  18682. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  18683. * to choose the wanted type.
  18684. * The parameter `size` (positive float, default 1) sets the polygon size.
  18685. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18686. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  18687. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  18688. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  18689. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  18690. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  18691. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18692. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18693. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18694. */
  18695. Mesh.CreatePolyhedron = function (name, options, scene) {
  18696. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18697. };
  18698. /**
  18699. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18700. * Please consider using the same method from the `MeshBuilder` class instead.
  18701. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18702. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  18703. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18704. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  18705. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18706. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18708. */
  18709. Mesh.CreateIcoSphere = function (name, options, scene) {
  18710. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18711. };
  18712. /**
  18713. * Creates a decal mesh.
  18714. * Please consider using the same method from the `MeshBuilder` class instead.
  18715. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  18716. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18717. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18718. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18719. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18720. */
  18721. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18722. var options = {
  18723. position: position,
  18724. normal: normal,
  18725. size: size,
  18726. angle: angle
  18727. };
  18728. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18729. };
  18730. // Skeletons
  18731. /**
  18732. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18733. */
  18734. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18735. var source;
  18736. if (!this._sourcePositions) {
  18737. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18738. this._sourcePositions = new Float32Array(source);
  18739. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18740. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18741. }
  18742. }
  18743. return this._sourcePositions;
  18744. };
  18745. /**
  18746. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18747. */
  18748. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18749. var source;
  18750. if (!this._sourceNormals) {
  18751. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18752. this._sourceNormals = new Float32Array(source);
  18753. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18754. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18755. }
  18756. }
  18757. return this._sourceNormals;
  18758. };
  18759. /**
  18760. * Update the vertex buffers by applying transformation from the bones
  18761. * @param {skeleton} skeleton to apply
  18762. */
  18763. Mesh.prototype.applySkeleton = function (skeleton) {
  18764. if (!this.geometry) {
  18765. return;
  18766. }
  18767. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18768. return;
  18769. }
  18770. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18771. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18772. return this;
  18773. }
  18774. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18775. return this;
  18776. }
  18777. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18778. return this;
  18779. }
  18780. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18781. return this;
  18782. }
  18783. if (!this._sourcePositions) {
  18784. this.setPositionsForCPUSkinning();
  18785. }
  18786. if (!this._sourceNormals) {
  18787. this.setNormalsForCPUSkinning();
  18788. }
  18789. // positionsData checks for not being Float32Array will only pass at most once
  18790. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18791. if (!(positionsData instanceof Float32Array)) {
  18792. positionsData = new Float32Array(positionsData);
  18793. }
  18794. // normalsData checks for not being Float32Array will only pass at most once
  18795. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18796. if (!(normalsData instanceof Float32Array)) {
  18797. normalsData = new Float32Array(normalsData);
  18798. }
  18799. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18800. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18801. var needExtras = this.numBoneInfluencers > 4;
  18802. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18803. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18804. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18805. var tempVector3 = BABYLON.Vector3.Zero();
  18806. var finalMatrix = new BABYLON.Matrix();
  18807. var tempMatrix = new BABYLON.Matrix();
  18808. var matWeightIdx = 0;
  18809. var inf;
  18810. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18811. var weight;
  18812. for (inf = 0; inf < 4; inf++) {
  18813. weight = matricesWeightsData[matWeightIdx + inf];
  18814. if (weight > 0) {
  18815. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18816. finalMatrix.addToSelf(tempMatrix);
  18817. }
  18818. else
  18819. break;
  18820. }
  18821. if (needExtras) {
  18822. for (inf = 0; inf < 4; inf++) {
  18823. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18824. if (weight > 0) {
  18825. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18826. finalMatrix.addToSelf(tempMatrix);
  18827. }
  18828. else
  18829. break;
  18830. }
  18831. }
  18832. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18833. tempVector3.toArray(positionsData, index);
  18834. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18835. tempVector3.toArray(normalsData, index);
  18836. finalMatrix.reset();
  18837. }
  18838. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18839. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18840. return this;
  18841. };
  18842. // Tools
  18843. Mesh.MinMax = function (meshes) {
  18844. var minVector = null;
  18845. var maxVector = null;
  18846. for (var i in meshes) {
  18847. var mesh = meshes[i];
  18848. var boundingBox = mesh.getBoundingInfo().boundingBox;
  18849. if (!minVector) {
  18850. minVector = boundingBox.minimumWorld;
  18851. maxVector = boundingBox.maximumWorld;
  18852. continue;
  18853. }
  18854. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  18855. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  18856. }
  18857. return {
  18858. min: minVector,
  18859. max: maxVector
  18860. };
  18861. };
  18862. Mesh.Center = function (meshesOrMinMaxVector) {
  18863. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  18864. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  18865. };
  18866. /**
  18867. * Merge the array of meshes into a single mesh for performance reasons.
  18868. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  18869. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  18870. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  18871. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  18872. */
  18873. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  18874. if (disposeSource === void 0) { disposeSource = true; }
  18875. var index;
  18876. if (!allow32BitsIndices) {
  18877. var totalVertices = 0;
  18878. // Counting vertices
  18879. for (index = 0; index < meshes.length; index++) {
  18880. if (meshes[index]) {
  18881. totalVertices += meshes[index].getTotalVertices();
  18882. if (totalVertices > 65536) {
  18883. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  18884. return null;
  18885. }
  18886. }
  18887. }
  18888. }
  18889. // Merge
  18890. var vertexData;
  18891. var otherVertexData;
  18892. var source;
  18893. for (index = 0; index < meshes.length; index++) {
  18894. if (meshes[index]) {
  18895. meshes[index].computeWorldMatrix(true);
  18896. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  18897. otherVertexData.transform(meshes[index].getWorldMatrix());
  18898. if (vertexData) {
  18899. vertexData.merge(otherVertexData);
  18900. }
  18901. else {
  18902. vertexData = otherVertexData;
  18903. source = meshes[index];
  18904. }
  18905. }
  18906. }
  18907. if (!meshSubclass) {
  18908. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  18909. }
  18910. vertexData.applyToMesh(meshSubclass);
  18911. // Setting properties
  18912. meshSubclass.material = source.material;
  18913. meshSubclass.checkCollisions = source.checkCollisions;
  18914. // Cleaning
  18915. if (disposeSource) {
  18916. for (index = 0; index < meshes.length; index++) {
  18917. if (meshes[index]) {
  18918. meshes[index].dispose();
  18919. }
  18920. }
  18921. }
  18922. return meshSubclass;
  18923. };
  18924. // Consts
  18925. Mesh._FRONTSIDE = 0;
  18926. Mesh._BACKSIDE = 1;
  18927. Mesh._DOUBLESIDE = 2;
  18928. Mesh._DEFAULTSIDE = 0;
  18929. Mesh._NO_CAP = 0;
  18930. Mesh._CAP_START = 1;
  18931. Mesh._CAP_END = 2;
  18932. Mesh._CAP_ALL = 3;
  18933. return Mesh;
  18934. })(BABYLON.AbstractMesh);
  18935. BABYLON.Mesh = Mesh;
  18936. })(BABYLON || (BABYLON = {}));
  18937. var BABYLON;
  18938. (function (BABYLON) {
  18939. var SubMesh = (function () {
  18940. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  18941. if (createBoundingBox === void 0) { createBoundingBox = true; }
  18942. this.materialIndex = materialIndex;
  18943. this.verticesStart = verticesStart;
  18944. this.verticesCount = verticesCount;
  18945. this.indexStart = indexStart;
  18946. this.indexCount = indexCount;
  18947. this._renderId = 0;
  18948. this._mesh = mesh;
  18949. this._renderingMesh = renderingMesh || mesh;
  18950. mesh.subMeshes.push(this);
  18951. this._trianglePlanes = [];
  18952. this._id = mesh.subMeshes.length - 1;
  18953. if (createBoundingBox) {
  18954. this.refreshBoundingInfo();
  18955. mesh.computeWorldMatrix(true);
  18956. }
  18957. }
  18958. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  18959. get: function () {
  18960. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  18961. },
  18962. enumerable: true,
  18963. configurable: true
  18964. });
  18965. SubMesh.prototype.getBoundingInfo = function () {
  18966. if (this.IsGlobal) {
  18967. return this._mesh.getBoundingInfo();
  18968. }
  18969. return this._boundingInfo;
  18970. };
  18971. SubMesh.prototype.getMesh = function () {
  18972. return this._mesh;
  18973. };
  18974. SubMesh.prototype.getRenderingMesh = function () {
  18975. return this._renderingMesh;
  18976. };
  18977. SubMesh.prototype.getMaterial = function () {
  18978. var rootMaterial = this._renderingMesh.material;
  18979. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  18980. var multiMaterial = rootMaterial;
  18981. return multiMaterial.getSubMaterial(this.materialIndex);
  18982. }
  18983. if (!rootMaterial) {
  18984. return this._mesh.getScene().defaultMaterial;
  18985. }
  18986. return rootMaterial;
  18987. };
  18988. // Methods
  18989. SubMesh.prototype.refreshBoundingInfo = function () {
  18990. this._lastColliderWorldVertices = null;
  18991. if (this.IsGlobal) {
  18992. return;
  18993. }
  18994. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18995. if (!data) {
  18996. this._boundingInfo = this._mesh._boundingInfo;
  18997. return;
  18998. }
  18999. var indices = this._renderingMesh.getIndices();
  19000. var extend;
  19001. //is this the only submesh?
  19002. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19003. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19004. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19005. }
  19006. else {
  19007. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19008. }
  19009. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19010. };
  19011. SubMesh.prototype._checkCollision = function (collider) {
  19012. return this.getBoundingInfo()._checkCollision(collider);
  19013. };
  19014. SubMesh.prototype.updateBoundingInfo = function (world) {
  19015. if (!this.getBoundingInfo()) {
  19016. this.refreshBoundingInfo();
  19017. }
  19018. this.getBoundingInfo().update(world);
  19019. };
  19020. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19021. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19022. };
  19023. SubMesh.prototype.render = function (enableAlphaMode) {
  19024. this._renderingMesh.render(this, enableAlphaMode);
  19025. };
  19026. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19027. if (!this._linesIndexBuffer) {
  19028. var linesIndices = [];
  19029. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19030. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19031. }
  19032. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19033. this.linesIndexCount = linesIndices.length;
  19034. }
  19035. return this._linesIndexBuffer;
  19036. };
  19037. SubMesh.prototype.canIntersects = function (ray) {
  19038. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19039. };
  19040. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19041. var intersectInfo = null;
  19042. // LineMesh first as it's also a Mesh...
  19043. if (this._mesh instanceof BABYLON.LinesMesh) {
  19044. var lineMesh = this._mesh;
  19045. // Line test
  19046. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19047. var p0 = positions[indices[index]];
  19048. var p1 = positions[indices[index + 1]];
  19049. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19050. if (length < 0) {
  19051. continue;
  19052. }
  19053. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19054. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19055. if (fastCheck) {
  19056. break;
  19057. }
  19058. }
  19059. }
  19060. }
  19061. else {
  19062. // Triangles test
  19063. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19064. var p0 = positions[indices[index]];
  19065. var p1 = positions[indices[index + 1]];
  19066. var p2 = positions[indices[index + 2]];
  19067. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19068. if (currentIntersectInfo) {
  19069. if (currentIntersectInfo.distance < 0) {
  19070. continue;
  19071. }
  19072. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19073. intersectInfo = currentIntersectInfo;
  19074. intersectInfo.faceId = index / 3;
  19075. if (fastCheck) {
  19076. break;
  19077. }
  19078. }
  19079. }
  19080. }
  19081. }
  19082. return intersectInfo;
  19083. };
  19084. // Clone
  19085. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19086. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19087. if (!this.IsGlobal) {
  19088. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19089. }
  19090. return result;
  19091. };
  19092. // Dispose
  19093. SubMesh.prototype.dispose = function () {
  19094. if (this._linesIndexBuffer) {
  19095. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19096. this._linesIndexBuffer = null;
  19097. }
  19098. // Remove from mesh
  19099. var index = this._mesh.subMeshes.indexOf(this);
  19100. this._mesh.subMeshes.splice(index, 1);
  19101. };
  19102. // Statics
  19103. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19104. var minVertexIndex = Number.MAX_VALUE;
  19105. var maxVertexIndex = -Number.MAX_VALUE;
  19106. renderingMesh = renderingMesh || mesh;
  19107. var indices = renderingMesh.getIndices();
  19108. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19109. var vertexIndex = indices[index];
  19110. if (vertexIndex < minVertexIndex)
  19111. minVertexIndex = vertexIndex;
  19112. if (vertexIndex > maxVertexIndex)
  19113. maxVertexIndex = vertexIndex;
  19114. }
  19115. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19116. };
  19117. return SubMesh;
  19118. })();
  19119. BABYLON.SubMesh = SubMesh;
  19120. })(BABYLON || (BABYLON = {}));
  19121. var BABYLON;
  19122. (function (BABYLON) {
  19123. var MeshBuilder = (function () {
  19124. function MeshBuilder() {
  19125. }
  19126. /**
  19127. * Creates a box mesh.
  19128. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19129. * The parameter `size` sets the size (float) of each box side (default 1).
  19130. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19131. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 `Color3` elements) and `faceUV` (an array of 6 `Vector4` elements).
  19132. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19133. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19134. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19135. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19136. */
  19137. MeshBuilder.CreateBox = function (name, options, scene) {
  19138. var box = new BABYLON.Mesh(name, scene);
  19139. var vertexData = BABYLON.VertexData.CreateBox(options);
  19140. vertexData.applyToMesh(box, options.updatable);
  19141. return box;
  19142. };
  19143. /**
  19144. * Creates a sphere mesh.
  19145. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19146. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19147. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  19148. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19149. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  19150. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  19151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19152. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19154. */
  19155. MeshBuilder.CreateSphere = function (name, options, scene) {
  19156. var sphere = new BABYLON.Mesh(name, scene);
  19157. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19158. vertexData.applyToMesh(sphere, options.updatable);
  19159. return sphere;
  19160. };
  19161. /**
  19162. * Creates a plane polygonal mesh. By default, this is a disc.
  19163. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19164. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19165. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  19166. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  19167. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19168. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19169. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19170. */
  19171. MeshBuilder.CreateDisc = function (name, options, scene) {
  19172. var disc = new BABYLON.Mesh(name, scene);
  19173. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19174. vertexData.applyToMesh(disc, options.updatable);
  19175. return disc;
  19176. };
  19177. /**
  19178. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19179. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19180. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19181. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  19182. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19183. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  19184. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19185. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19187. */
  19188. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19189. var sphere = new BABYLON.Mesh(name, scene);
  19190. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19191. vertexData.applyToMesh(sphere, options.updatable);
  19192. return sphere;
  19193. };
  19194. ;
  19195. /**
  19196. * Creates a ribbon mesh.
  19197. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19198. *
  19199. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19200. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19201. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19202. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19203. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  19204. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  19205. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  19206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19207. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19209. */
  19210. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19211. var pathArray = options.pathArray;
  19212. var closeArray = options.closeArray;
  19213. var closePath = options.closePath;
  19214. var offset = options.offset;
  19215. var sideOrientation = options.sideOrientation;
  19216. var instance = options.instance;
  19217. var updatable = options.updatable;
  19218. if (instance) {
  19219. // positionFunction : ribbon case
  19220. // only pathArray and sideOrientation parameters are taken into account for positions update
  19221. var positionFunction = function (positions) {
  19222. var minlg = pathArray[0].length;
  19223. var i = 0;
  19224. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19225. for (var si = 1; si <= ns; si++) {
  19226. for (var p = 0; p < pathArray.length; p++) {
  19227. var path = pathArray[p];
  19228. var l = path.length;
  19229. minlg = (minlg < l) ? minlg : l;
  19230. var j = 0;
  19231. while (j < minlg) {
  19232. positions[i] = path[j].x;
  19233. positions[i + 1] = path[j].y;
  19234. positions[i + 2] = path[j].z;
  19235. j++;
  19236. i += 3;
  19237. }
  19238. if (instance._closePath) {
  19239. positions[i] = path[0].x;
  19240. positions[i + 1] = path[0].y;
  19241. positions[i + 2] = path[0].z;
  19242. i += 3;
  19243. }
  19244. }
  19245. }
  19246. };
  19247. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19248. positionFunction(positions);
  19249. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19250. if (!(instance.areNormalsFrozen)) {
  19251. var indices = instance.getIndices();
  19252. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19253. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19254. if (instance._closePath) {
  19255. var indexFirst = 0;
  19256. var indexLast = 0;
  19257. for (var p = 0; p < pathArray.length; p++) {
  19258. indexFirst = instance._idx[p] * 3;
  19259. if (p + 1 < pathArray.length) {
  19260. indexLast = (instance._idx[p + 1] - 1) * 3;
  19261. }
  19262. else {
  19263. indexLast = normals.length - 3;
  19264. }
  19265. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19266. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19267. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19268. normals[indexLast] = normals[indexFirst];
  19269. normals[indexLast + 1] = normals[indexFirst + 1];
  19270. normals[indexLast + 2] = normals[indexFirst + 2];
  19271. }
  19272. }
  19273. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19274. }
  19275. return instance;
  19276. }
  19277. else {
  19278. var ribbon = new BABYLON.Mesh(name, scene);
  19279. ribbon.sideOrientation = sideOrientation;
  19280. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19281. if (closePath) {
  19282. ribbon._idx = vertexData._idx;
  19283. }
  19284. ribbon._closePath = closePath;
  19285. ribbon._closeArray = closeArray;
  19286. vertexData.applyToMesh(ribbon, updatable);
  19287. return ribbon;
  19288. }
  19289. };
  19290. /**
  19291. * Creates a cylinder or a cone mesh.
  19292. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19293. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19294. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19295. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  19296. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19297. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19298. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19299. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19300. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19301. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n `Color3` elements) and `faceUV` (an array of n `Vector4` elements).
  19302. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  19303. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19304. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  19305. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  19306. * If `enclose` is false, a ring surface is one element.
  19307. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19308. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  19309. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19310. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19311. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19312. */
  19313. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19314. var cylinder = new BABYLON.Mesh(name, scene);
  19315. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19316. vertexData.applyToMesh(cylinder, options.updatable);
  19317. return cylinder;
  19318. };
  19319. /**
  19320. * Creates a torus mesh.
  19321. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19322. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19323. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19324. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19325. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19326. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19328. */
  19329. MeshBuilder.CreateTorus = function (name, options, scene) {
  19330. var torus = new BABYLON.Mesh(name, scene);
  19331. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19332. vertexData.applyToMesh(torus, options.updatable);
  19333. return torus;
  19334. };
  19335. /**
  19336. * Creates a torus knot mesh.
  19337. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19338. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19339. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19340. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19341. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19342. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19344. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19345. */
  19346. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19347. var torusKnot = new BABYLON.Mesh(name, scene);
  19348. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19349. vertexData.applyToMesh(torusKnot, options.updatable);
  19350. return torusKnot;
  19351. };
  19352. /**
  19353. * Creates a line system mesh.
  19354. * A line system is a pool of many lines gathered in a single mesh.
  19355. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19356. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  19357. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19358. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19359. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  19360. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19361. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19362. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19363. */
  19364. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19365. var instance = options.instance;
  19366. var lines = options.lines;
  19367. if (instance) {
  19368. var positionFunction = function (positions) {
  19369. var i = 0;
  19370. for (var l = 0; l < lines.length; l++) {
  19371. var points = lines[l];
  19372. for (var p = 0; p < points.length; p++) {
  19373. positions[i] = points[p].x;
  19374. positions[i + 1] = points[p].y;
  19375. positions[i + 2] = points[p].z;
  19376. i += 3;
  19377. }
  19378. }
  19379. };
  19380. instance.updateMeshPositions(positionFunction, false);
  19381. return instance;
  19382. }
  19383. // line system creation
  19384. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19385. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19386. vertexData.applyToMesh(lineSystem, options.updatable);
  19387. return lineSystem;
  19388. };
  19389. /**
  19390. * Creates a line mesh.
  19391. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19392. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19393. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19394. * The parameter `points` is an array successive Vector3.
  19395. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19396. * When updating an instance, remember that only point positions can change, not the number of points.
  19397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19398. */
  19399. MeshBuilder.CreateLines = function (name, options, scene) {
  19400. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19401. return lines;
  19402. };
  19403. /**
  19404. * Creates a dashed line mesh.
  19405. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19406. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  19407. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19408. * The parameter `points` is an array successive Vector3.
  19409. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19410. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19411. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19412. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  19413. * When updating an instance, remember that only point positions can change, not the number of points.
  19414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19415. */
  19416. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19417. var points = options.points;
  19418. var instance = options.instance;
  19419. var gapSize = options.gapSize;
  19420. var dashNb = options.dashNb;
  19421. var dashSize = options.dashSize;
  19422. if (instance) {
  19423. var positionFunction = function (positions) {
  19424. var curvect = BABYLON.Vector3.Zero();
  19425. var nbSeg = positions.length / 6;
  19426. var lg = 0;
  19427. var nb = 0;
  19428. var shft = 0;
  19429. var dashshft = 0;
  19430. var curshft = 0;
  19431. var p = 0;
  19432. var i = 0;
  19433. var j = 0;
  19434. for (i = 0; i < points.length - 1; i++) {
  19435. points[i + 1].subtractToRef(points[i], curvect);
  19436. lg += curvect.length();
  19437. }
  19438. shft = lg / nbSeg;
  19439. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19440. for (i = 0; i < points.length - 1; i++) {
  19441. points[i + 1].subtractToRef(points[i], curvect);
  19442. nb = Math.floor(curvect.length() / shft);
  19443. curvect.normalize();
  19444. j = 0;
  19445. while (j < nb && p < positions.length) {
  19446. curshft = shft * j;
  19447. positions[p] = points[i].x + curshft * curvect.x;
  19448. positions[p + 1] = points[i].y + curshft * curvect.y;
  19449. positions[p + 2] = points[i].z + curshft * curvect.z;
  19450. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19451. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19452. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19453. p += 6;
  19454. j++;
  19455. }
  19456. }
  19457. while (p < positions.length) {
  19458. positions[p] = points[i].x;
  19459. positions[p + 1] = points[i].y;
  19460. positions[p + 2] = points[i].z;
  19461. p += 3;
  19462. }
  19463. };
  19464. instance.updateMeshPositions(positionFunction, false);
  19465. return instance;
  19466. }
  19467. // dashed lines creation
  19468. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19469. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19470. vertexData.applyToMesh(dashedLines, options.updatable);
  19471. dashedLines.dashSize = dashSize;
  19472. dashedLines.gapSize = gapSize;
  19473. return dashedLines;
  19474. };
  19475. /**
  19476. * Creates an extruded shape mesh.
  19477. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19478. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19479. *
  19480. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19481. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19482. * extruded along the Z axis.
  19483. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19484. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  19485. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19486. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19487. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19488. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19492. */
  19493. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19494. var path = options.path;
  19495. var shape = options.shape;
  19496. var scale = options.scale || 1;
  19497. var rotation = options.rotation || 0;
  19498. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19499. var updatable = options.updatable;
  19500. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19501. var instance = options.instance;
  19502. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19503. };
  19504. /**
  19505. * Creates an custom extruded shape mesh.
  19506. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19507. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19508. *
  19509. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19510. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  19511. * extruded along the Z axis.
  19512. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19513. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19514. * and the distance of this point from the begining of the path :
  19515. * ```rotationFunction = function(i, distance) {
  19516. * // do things
  19517. * return rotationValue; }```
  19518. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19519. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  19520. * and the distance of this point from the begining of the path :
  19521. * ````scaleFunction = function(i, distance) {
  19522. * // do things
  19523. * return scaleValue;}```
  19524. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19525. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19526. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19527. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19528. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  19529. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19533. */
  19534. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19535. var path = options.path;
  19536. var shape = options.shape;
  19537. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19538. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19539. var ribbonCloseArray = options.ribbonCloseArray || false;
  19540. var ribbonClosePath = options.ribbonClosePath || false;
  19541. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19542. var updatable = options.updatable;
  19543. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19544. var instance = options.instance;
  19545. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19546. };
  19547. /**
  19548. * Creates lathe mesh.
  19549. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19550. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19551. *
  19552. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  19553. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19554. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19555. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19556. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  19557. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19558. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19562. */
  19563. MeshBuilder.CreateLathe = function (name, options, scene) {
  19564. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19565. var closed = (options.closed === undefined) ? true : options.closed;
  19566. var shape = options.shape;
  19567. var radius = options.radius || 1;
  19568. var tessellation = options.tessellation || 64;
  19569. var updatable = options.updatable;
  19570. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19571. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19572. var pi2 = Math.PI * 2;
  19573. var paths = new Array();
  19574. var i = 0;
  19575. var p = 0;
  19576. var step = pi2 / tessellation * arc;
  19577. var rotated;
  19578. var path = new Array();
  19579. ;
  19580. for (i = 0; i <= tessellation; i++) {
  19581. var path = [];
  19582. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19583. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19584. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19585. }
  19586. for (p = 0; p < shape.length; p++) {
  19587. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19588. path.push(rotated);
  19589. }
  19590. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19591. 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));
  19592. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19593. }
  19594. paths.push(path);
  19595. }
  19596. // lathe ribbon
  19597. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19598. return lathe;
  19599. };
  19600. /**
  19601. * Creates a plane mesh.
  19602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19603. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19604. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19605. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19606. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19607. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19609. */
  19610. MeshBuilder.CreatePlane = function (name, options, scene) {
  19611. var plane = new BABYLON.Mesh(name, scene);
  19612. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19613. vertexData.applyToMesh(plane, options.updatable);
  19614. if (options.sourcePlane) {
  19615. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19616. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19617. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19618. plane.rotate(vectorProduct, product);
  19619. }
  19620. return plane;
  19621. };
  19622. /**
  19623. * Creates a ground mesh.
  19624. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19625. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19626. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19628. */
  19629. MeshBuilder.CreateGround = function (name, options, scene) {
  19630. var ground = new BABYLON.GroundMesh(name, scene);
  19631. ground._setReady(false);
  19632. ground._subdivisions = options.subdivisions || 1;
  19633. ground._width = options.width || 1;
  19634. ground._height = options.height || 1;
  19635. ground._maxX = ground._width / 2;
  19636. ground._maxZ = ground._height / 2;
  19637. ground._minX = -ground._maxX;
  19638. ground._minZ = -ground._maxZ;
  19639. var vertexData = BABYLON.VertexData.CreateGround(options);
  19640. vertexData.applyToMesh(ground, options.updatable);
  19641. ground._setReady(true);
  19642. return ground;
  19643. };
  19644. /**
  19645. * Creates a tiled ground mesh.
  19646. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19647. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19648. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19649. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19650. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19651. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19652. * numbers of subdivisions on the ground width and height of each tile.
  19653. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19654. */
  19655. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19656. var tiledGround = new BABYLON.Mesh(name, scene);
  19657. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19658. vertexData.applyToMesh(tiledGround, options.updatable);
  19659. return tiledGround;
  19660. };
  19661. /**
  19662. * Creates a ground mesh from a height map.
  19663. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19664. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19665. * The parameter `url` sets the URL of the height map image resource.
  19666. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19667. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19668. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19669. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19670. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  19671. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19672. * return; }```
  19673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19674. */
  19675. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19676. var width = options.width || 10;
  19677. var height = options.height || 10;
  19678. var subdivisions = options.subdivisions || 1;
  19679. var minHeight = options.minHeight;
  19680. var maxHeight = options.maxHeight || 10;
  19681. var updatable = options.updatable;
  19682. var onReady = options.onReady;
  19683. var ground = new BABYLON.GroundMesh(name, scene);
  19684. ground._subdivisions = subdivisions;
  19685. ground._width = width;
  19686. ground._height = height;
  19687. ground._maxX = ground._width / 2;
  19688. ground._maxZ = ground._height / 2;
  19689. ground._minX = -ground._maxX;
  19690. ground._minZ = -ground._maxZ;
  19691. ground._setReady(false);
  19692. var onload = function (img) {
  19693. // Getting height map data
  19694. var canvas = document.createElement("canvas");
  19695. var context = canvas.getContext("2d");
  19696. var bufferWidth = img.width;
  19697. var bufferHeight = img.height;
  19698. canvas.width = bufferWidth;
  19699. canvas.height = bufferHeight;
  19700. context.drawImage(img, 0, 0);
  19701. // Create VertexData from map data
  19702. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19703. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19704. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19705. width: width, height: height,
  19706. subdivisions: subdivisions,
  19707. minHeight: minHeight, maxHeight: maxHeight,
  19708. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19709. });
  19710. vertexData.applyToMesh(ground, updatable);
  19711. ground._setReady(true);
  19712. //execute ready callback, if set
  19713. if (onReady) {
  19714. onReady(ground);
  19715. }
  19716. };
  19717. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19718. return ground;
  19719. };
  19720. /**
  19721. * Creates a tube mesh.
  19722. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  19723. *
  19724. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19725. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19726. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19727. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19728. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19729. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  19730. * It must return a radius value (positive float) :
  19731. * ```var radiusFunction = function(i, distance) {
  19732. * // do things
  19733. * return radius; }```
  19734. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19735. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19736. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  19737. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19738. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19739. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19740. */
  19741. MeshBuilder.CreateTube = function (name, options, scene) {
  19742. var path = options.path;
  19743. var radius = options.radius || 1;
  19744. var tessellation = options.tessellation || 64;
  19745. var radiusFunction = options.radiusFunction;
  19746. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19747. var updatable = options.updatable;
  19748. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19749. var instance = options.instance;
  19750. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19751. // tube geometry
  19752. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19753. var tangents = path3D.getTangents();
  19754. var normals = path3D.getNormals();
  19755. var distances = path3D.getDistances();
  19756. var pi2 = Math.PI * 2;
  19757. var step = pi2 / tessellation * arc;
  19758. var returnRadius = function () { return radius; };
  19759. var radiusFunctionFinal = radiusFunction || returnRadius;
  19760. var circlePath;
  19761. var rad;
  19762. var normal;
  19763. var rotated;
  19764. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19765. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19766. for (var i = 0; i < path.length; i++) {
  19767. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19768. circlePath = Array(); // current circle array
  19769. normal = normals[i]; // current normal
  19770. for (var t = 0; t < tessellation; t++) {
  19771. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19772. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19773. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19774. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19775. circlePath[t] = rotated;
  19776. }
  19777. circlePaths[index] = circlePath;
  19778. index++;
  19779. }
  19780. // cap
  19781. var capPath = function (nbPoints, pathIndex) {
  19782. var pointCap = Array();
  19783. for (var i = 0; i < nbPoints; i++) {
  19784. pointCap.push(path[pathIndex]);
  19785. }
  19786. return pointCap;
  19787. };
  19788. switch (cap) {
  19789. case BABYLON.Mesh.NO_CAP:
  19790. break;
  19791. case BABYLON.Mesh.CAP_START:
  19792. circlePaths[0] = capPath(tessellation, 0);
  19793. circlePaths[1] = circlePaths[2].slice(0);
  19794. break;
  19795. case BABYLON.Mesh.CAP_END:
  19796. circlePaths[index] = circlePaths[index - 1].slice(0);
  19797. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19798. break;
  19799. case BABYLON.Mesh.CAP_ALL:
  19800. circlePaths[0] = capPath(tessellation, 0);
  19801. circlePaths[1] = circlePaths[2].slice(0);
  19802. circlePaths[index] = circlePaths[index - 1].slice(0);
  19803. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19804. break;
  19805. default:
  19806. break;
  19807. }
  19808. return circlePaths;
  19809. };
  19810. var path3D;
  19811. var pathArray;
  19812. if (instance) {
  19813. var arc = options.arc || instance.arc;
  19814. path3D = (instance.path3D).update(path);
  19815. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19816. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19817. instance.path3D = path3D;
  19818. instance.pathArray = pathArray;
  19819. instance.arc = arc;
  19820. return instance;
  19821. }
  19822. // tube creation
  19823. path3D = new BABYLON.Path3D(path);
  19824. var newPathArray = new Array();
  19825. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19826. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19827. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19828. tube.pathArray = pathArray;
  19829. tube.path3D = path3D;
  19830. tube.tessellation = tessellation;
  19831. tube.cap = cap;
  19832. tube.arc = options.arc;
  19833. return tube;
  19834. };
  19835. /**
  19836. * Creates a polyhedron mesh.
  19837. *
  19838. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  19839. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  19840. * to choose the wanted type.
  19841. * The parameter `size` (positive float, default 1) sets the polygon size.
  19842. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19843. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  19844. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  19845. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (`Color4`, default `(1, 1, 1, 1)`) and faceUV (`Vector4`, default `(0, 0, 1, 1)`).
  19846. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19847. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  19848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19851. */
  19852. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  19853. var polyhedron = new BABYLON.Mesh(name, scene);
  19854. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  19855. vertexData.applyToMesh(polyhedron, options.updatable);
  19856. return polyhedron;
  19857. };
  19858. /**
  19859. * Creates a decal mesh.
  19860. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  19861. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  19862. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19863. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19864. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19865. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19866. */
  19867. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  19868. var indices = sourceMesh.getIndices();
  19869. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19870. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19871. var position = options.position || BABYLON.Vector3.Zero();
  19872. var normal = options.normal || BABYLON.Vector3.Up();
  19873. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  19874. var angle = options.angle || 0;
  19875. // Getting correct rotation
  19876. if (!normal) {
  19877. var target = new BABYLON.Vector3(0, 0, 1);
  19878. var camera = sourceMesh.getScene().activeCamera;
  19879. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  19880. normal = camera.globalPosition.subtract(cameraWorldTarget);
  19881. }
  19882. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  19883. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  19884. var pitch = Math.atan2(normal.y, len);
  19885. // Matrix
  19886. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  19887. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  19888. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  19889. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  19890. var vertexData = new BABYLON.VertexData();
  19891. vertexData.indices = [];
  19892. vertexData.positions = [];
  19893. vertexData.normals = [];
  19894. vertexData.uvs = [];
  19895. var currentVertexDataIndex = 0;
  19896. var extractDecalVector3 = function (indexId) {
  19897. var vertexId = indices[indexId];
  19898. var result = new BABYLON.PositionNormalVertex();
  19899. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  19900. // Send vector to decal local world
  19901. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  19902. // Get normal
  19903. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  19904. return result;
  19905. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  19906. var clip = function (vertices, axis) {
  19907. if (vertices.length === 0) {
  19908. return vertices;
  19909. }
  19910. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  19911. var clipVertices = function (v0, v1) {
  19912. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  19913. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  19914. };
  19915. var result = new Array();
  19916. for (var index = 0; index < vertices.length; index += 3) {
  19917. var v1Out;
  19918. var v2Out;
  19919. var v3Out;
  19920. var total = 0;
  19921. var nV1, nV2, nV3, nV4;
  19922. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  19923. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  19924. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  19925. v1Out = d1 > 0;
  19926. v2Out = d2 > 0;
  19927. v3Out = d3 > 0;
  19928. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  19929. switch (total) {
  19930. case 0:
  19931. result.push(vertices[index]);
  19932. result.push(vertices[index + 1]);
  19933. result.push(vertices[index + 2]);
  19934. break;
  19935. case 1:
  19936. if (v1Out) {
  19937. nV1 = vertices[index + 1];
  19938. nV2 = vertices[index + 2];
  19939. nV3 = clipVertices(vertices[index], nV1);
  19940. nV4 = clipVertices(vertices[index], nV2);
  19941. }
  19942. if (v2Out) {
  19943. nV1 = vertices[index];
  19944. nV2 = vertices[index + 2];
  19945. nV3 = clipVertices(vertices[index + 1], nV1);
  19946. nV4 = clipVertices(vertices[index + 1], nV2);
  19947. result.push(nV3);
  19948. result.push(nV2.clone());
  19949. result.push(nV1.clone());
  19950. result.push(nV2.clone());
  19951. result.push(nV3.clone());
  19952. result.push(nV4);
  19953. break;
  19954. }
  19955. if (v3Out) {
  19956. nV1 = vertices[index];
  19957. nV2 = vertices[index + 1];
  19958. nV3 = clipVertices(vertices[index + 2], nV1);
  19959. nV4 = clipVertices(vertices[index + 2], nV2);
  19960. }
  19961. result.push(nV1.clone());
  19962. result.push(nV2.clone());
  19963. result.push(nV3);
  19964. result.push(nV4);
  19965. result.push(nV3.clone());
  19966. result.push(nV2.clone());
  19967. break;
  19968. case 2:
  19969. if (!v1Out) {
  19970. nV1 = vertices[index].clone();
  19971. nV2 = clipVertices(nV1, vertices[index + 1]);
  19972. nV3 = clipVertices(nV1, vertices[index + 2]);
  19973. result.push(nV1);
  19974. result.push(nV2);
  19975. result.push(nV3);
  19976. }
  19977. if (!v2Out) {
  19978. nV1 = vertices[index + 1].clone();
  19979. nV2 = clipVertices(nV1, vertices[index + 2]);
  19980. nV3 = clipVertices(nV1, vertices[index]);
  19981. result.push(nV1);
  19982. result.push(nV2);
  19983. result.push(nV3);
  19984. }
  19985. if (!v3Out) {
  19986. nV1 = vertices[index + 2].clone();
  19987. nV2 = clipVertices(nV1, vertices[index]);
  19988. nV3 = clipVertices(nV1, vertices[index + 1]);
  19989. result.push(nV1);
  19990. result.push(nV2);
  19991. result.push(nV3);
  19992. }
  19993. break;
  19994. case 3:
  19995. break;
  19996. }
  19997. }
  19998. return result;
  19999. };
  20000. for (var index = 0; index < indices.length; index += 3) {
  20001. var faceVertices = new Array();
  20002. faceVertices.push(extractDecalVector3(index));
  20003. faceVertices.push(extractDecalVector3(index + 1));
  20004. faceVertices.push(extractDecalVector3(index + 2));
  20005. // Clip
  20006. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20007. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20008. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20009. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20010. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20011. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20012. if (faceVertices.length === 0) {
  20013. continue;
  20014. }
  20015. // Add UVs and get back to world
  20016. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20017. var vertex = faceVertices[vIndex];
  20018. //TODO check for Int32Array
  20019. vertexData.indices.push(currentVertexDataIndex);
  20020. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20021. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20022. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20023. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20024. currentVertexDataIndex++;
  20025. }
  20026. }
  20027. // Return mesh
  20028. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20029. vertexData.applyToMesh(decal);
  20030. decal.position = position.clone();
  20031. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20032. return decal;
  20033. };
  20034. // Privates
  20035. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20036. // extrusion geometry
  20037. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20038. var tangents = path3D.getTangents();
  20039. var normals = path3D.getNormals();
  20040. var binormals = path3D.getBinormals();
  20041. var distances = path3D.getDistances();
  20042. var angle = 0;
  20043. var returnScale = function () { return scale; };
  20044. var returnRotation = function () { return rotation; };
  20045. var rotate = custom ? rotateFunction : returnRotation;
  20046. var scl = custom ? scaleFunction : returnScale;
  20047. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20048. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20049. for (var i = 0; i < curve.length; i++) {
  20050. var shapePath = new Array();
  20051. var angleStep = rotate(i, distances[i]);
  20052. var scaleRatio = scl(i, distances[i]);
  20053. for (var p = 0; p < shape.length; p++) {
  20054. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20055. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20056. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20057. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20058. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20059. shapePath[p] = rotated;
  20060. }
  20061. shapePaths[index] = shapePath;
  20062. angle += angleStep;
  20063. index++;
  20064. }
  20065. // cap
  20066. var capPath = function (shapePath) {
  20067. var pointCap = Array();
  20068. var barycenter = BABYLON.Vector3.Zero();
  20069. var i;
  20070. for (i = 0; i < shapePath.length; i++) {
  20071. barycenter.addInPlace(shapePath[i]);
  20072. }
  20073. barycenter.scaleInPlace(1 / shapePath.length);
  20074. for (i = 0; i < shapePath.length; i++) {
  20075. pointCap.push(barycenter);
  20076. }
  20077. return pointCap;
  20078. };
  20079. switch (cap) {
  20080. case BABYLON.Mesh.NO_CAP:
  20081. break;
  20082. case BABYLON.Mesh.CAP_START:
  20083. shapePaths[0] = capPath(shapePaths[2]);
  20084. shapePaths[1] = shapePaths[2].slice(0);
  20085. break;
  20086. case BABYLON.Mesh.CAP_END:
  20087. shapePaths[index] = shapePaths[index - 1];
  20088. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20089. break;
  20090. case BABYLON.Mesh.CAP_ALL:
  20091. shapePaths[0] = capPath(shapePaths[2]);
  20092. shapePaths[1] = shapePaths[2].slice(0);
  20093. shapePaths[index] = shapePaths[index - 1];
  20094. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20095. break;
  20096. default:
  20097. break;
  20098. }
  20099. return shapePaths;
  20100. };
  20101. var path3D;
  20102. var pathArray;
  20103. if (instance) {
  20104. path3D = (instance.path3D).update(curve);
  20105. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20106. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20107. return instance;
  20108. }
  20109. // extruded shape creation
  20110. path3D = new BABYLON.Path3D(curve);
  20111. var newShapePaths = new Array();
  20112. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20113. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20114. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20115. extrudedGeneric.pathArray = pathArray;
  20116. extrudedGeneric.path3D = path3D;
  20117. extrudedGeneric.cap = cap;
  20118. return extrudedGeneric;
  20119. };
  20120. return MeshBuilder;
  20121. })();
  20122. BABYLON.MeshBuilder = MeshBuilder;
  20123. })(BABYLON || (BABYLON = {}));
  20124. var BABYLON;
  20125. (function (BABYLON) {
  20126. var BaseTexture = (function () {
  20127. function BaseTexture(scene) {
  20128. this.hasAlpha = false;
  20129. this.getAlphaFromRGB = false;
  20130. this.level = 1;
  20131. this.coordinatesIndex = 0;
  20132. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20133. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20134. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20135. this.anisotropicFilteringLevel = 4;
  20136. this.isCube = false;
  20137. this.isRenderTarget = false;
  20138. this.animations = new Array();
  20139. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20140. this._scene = scene;
  20141. this._scene.textures.push(this);
  20142. }
  20143. BaseTexture.prototype.getScene = function () {
  20144. return this._scene;
  20145. };
  20146. BaseTexture.prototype.getTextureMatrix = function () {
  20147. return null;
  20148. };
  20149. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20150. return null;
  20151. };
  20152. BaseTexture.prototype.getInternalTexture = function () {
  20153. return this._texture;
  20154. };
  20155. BaseTexture.prototype.isReady = function () {
  20156. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20157. return true;
  20158. }
  20159. if (this._texture) {
  20160. return this._texture.isReady;
  20161. }
  20162. return false;
  20163. };
  20164. BaseTexture.prototype.getSize = function () {
  20165. if (this._texture._width) {
  20166. return { width: this._texture._width, height: this._texture._height };
  20167. }
  20168. if (this._texture._size) {
  20169. return { width: this._texture._size, height: this._texture._size };
  20170. }
  20171. return { width: 0, height: 0 };
  20172. };
  20173. BaseTexture.prototype.getBaseSize = function () {
  20174. if (!this.isReady() || !this._texture)
  20175. return { width: 0, height: 0 };
  20176. if (this._texture._size) {
  20177. return { width: this._texture._size, height: this._texture._size };
  20178. }
  20179. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20180. };
  20181. BaseTexture.prototype.scale = function (ratio) {
  20182. };
  20183. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20184. get: function () {
  20185. return false;
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20191. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20192. for (var index = 0; index < texturesCache.length; index++) {
  20193. var texturesCacheEntry = texturesCache[index];
  20194. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20195. texturesCache.splice(index, 1);
  20196. return;
  20197. }
  20198. }
  20199. };
  20200. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20201. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20202. for (var index = 0; index < texturesCache.length; index++) {
  20203. var texturesCacheEntry = texturesCache[index];
  20204. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20205. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20206. texturesCacheEntry.references++;
  20207. return texturesCacheEntry;
  20208. }
  20209. }
  20210. }
  20211. return null;
  20212. };
  20213. BaseTexture.prototype.delayLoad = function () {
  20214. };
  20215. BaseTexture.prototype.clone = function () {
  20216. return null;
  20217. };
  20218. BaseTexture.prototype.releaseInternalTexture = function () {
  20219. if (this._texture) {
  20220. this._scene.getEngine().releaseInternalTexture(this._texture);
  20221. delete this._texture;
  20222. }
  20223. };
  20224. BaseTexture.prototype.dispose = function () {
  20225. // Animations
  20226. this.getScene().stopAnimation(this);
  20227. // Remove from scene
  20228. var index = this._scene.textures.indexOf(this);
  20229. if (index >= 0) {
  20230. this._scene.textures.splice(index, 1);
  20231. }
  20232. if (this._texture === undefined) {
  20233. return;
  20234. }
  20235. // Release
  20236. this.releaseInternalTexture();
  20237. // Callback
  20238. if (this.onDispose) {
  20239. this.onDispose();
  20240. }
  20241. };
  20242. BaseTexture.prototype.serialize = function () {
  20243. if (!this.name) {
  20244. return null;
  20245. }
  20246. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20247. // Animations
  20248. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20249. return serializationObject;
  20250. };
  20251. __decorate([
  20252. BABYLON.serialize()
  20253. ], BaseTexture.prototype, "name", void 0);
  20254. __decorate([
  20255. BABYLON.serialize()
  20256. ], BaseTexture.prototype, "hasAlpha", void 0);
  20257. __decorate([
  20258. BABYLON.serialize()
  20259. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20260. __decorate([
  20261. BABYLON.serialize()
  20262. ], BaseTexture.prototype, "level", void 0);
  20263. __decorate([
  20264. BABYLON.serialize()
  20265. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20266. __decorate([
  20267. BABYLON.serialize()
  20268. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20269. __decorate([
  20270. BABYLON.serialize()
  20271. ], BaseTexture.prototype, "wrapU", void 0);
  20272. __decorate([
  20273. BABYLON.serialize()
  20274. ], BaseTexture.prototype, "wrapV", void 0);
  20275. __decorate([
  20276. BABYLON.serialize()
  20277. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20278. __decorate([
  20279. BABYLON.serialize()
  20280. ], BaseTexture.prototype, "isCube", void 0);
  20281. __decorate([
  20282. BABYLON.serialize()
  20283. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20284. return BaseTexture;
  20285. })();
  20286. BABYLON.BaseTexture = BaseTexture;
  20287. })(BABYLON || (BABYLON = {}));
  20288. var BABYLON;
  20289. (function (BABYLON) {
  20290. var Texture = (function (_super) {
  20291. __extends(Texture, _super);
  20292. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20293. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20294. if (onLoad === void 0) { onLoad = null; }
  20295. if (onError === void 0) { onError = null; }
  20296. if (buffer === void 0) { buffer = null; }
  20297. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20298. _super.call(this, scene);
  20299. this.uOffset = 0;
  20300. this.vOffset = 0;
  20301. this.uScale = 1.0;
  20302. this.vScale = 1.0;
  20303. this.uAng = 0;
  20304. this.vAng = 0;
  20305. this.wAng = 0;
  20306. this.name = url;
  20307. this.url = url;
  20308. this._noMipmap = noMipmap;
  20309. this._invertY = invertY;
  20310. this._samplingMode = samplingMode;
  20311. this._buffer = buffer;
  20312. this._deleteBuffer = deleteBuffer;
  20313. if (!url) {
  20314. return;
  20315. }
  20316. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20317. if (!this._texture) {
  20318. if (!scene.useDelayedTextureLoading) {
  20319. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20320. if (deleteBuffer) {
  20321. delete this._buffer;
  20322. }
  20323. }
  20324. else {
  20325. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20326. this._delayedOnLoad = onLoad;
  20327. this._delayedOnError = onError;
  20328. }
  20329. }
  20330. else {
  20331. BABYLON.Tools.SetImmediate(function () {
  20332. if (onLoad) {
  20333. onLoad();
  20334. }
  20335. });
  20336. }
  20337. }
  20338. Texture.prototype.delayLoad = function () {
  20339. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20340. return;
  20341. }
  20342. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20343. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20344. if (!this._texture) {
  20345. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20346. if (this._deleteBuffer) {
  20347. delete this._buffer;
  20348. }
  20349. }
  20350. };
  20351. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20352. if (!this._texture) {
  20353. return;
  20354. }
  20355. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20356. };
  20357. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20358. x *= this.uScale;
  20359. y *= this.vScale;
  20360. x -= 0.5 * this.uScale;
  20361. y -= 0.5 * this.vScale;
  20362. z -= 0.5;
  20363. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20364. t.x += 0.5 * this.uScale + this.uOffset;
  20365. t.y += 0.5 * this.vScale + this.vOffset;
  20366. t.z += 0.5;
  20367. };
  20368. Texture.prototype.getTextureMatrix = function () {
  20369. if (this.uOffset === this._cachedUOffset &&
  20370. this.vOffset === this._cachedVOffset &&
  20371. this.uScale === this._cachedUScale &&
  20372. this.vScale === this._cachedVScale &&
  20373. this.uAng === this._cachedUAng &&
  20374. this.vAng === this._cachedVAng &&
  20375. this.wAng === this._cachedWAng) {
  20376. return this._cachedTextureMatrix;
  20377. }
  20378. this._cachedUOffset = this.uOffset;
  20379. this._cachedVOffset = this.vOffset;
  20380. this._cachedUScale = this.uScale;
  20381. this._cachedVScale = this.vScale;
  20382. this._cachedUAng = this.uAng;
  20383. this._cachedVAng = this.vAng;
  20384. this._cachedWAng = this.wAng;
  20385. if (!this._cachedTextureMatrix) {
  20386. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20387. this._rowGenerationMatrix = new BABYLON.Matrix();
  20388. this._t0 = BABYLON.Vector3.Zero();
  20389. this._t1 = BABYLON.Vector3.Zero();
  20390. this._t2 = BABYLON.Vector3.Zero();
  20391. }
  20392. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20393. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20394. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20395. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20396. this._t1.subtractInPlace(this._t0);
  20397. this._t2.subtractInPlace(this._t0);
  20398. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20399. this._cachedTextureMatrix.m[0] = this._t1.x;
  20400. this._cachedTextureMatrix.m[1] = this._t1.y;
  20401. this._cachedTextureMatrix.m[2] = this._t1.z;
  20402. this._cachedTextureMatrix.m[4] = this._t2.x;
  20403. this._cachedTextureMatrix.m[5] = this._t2.y;
  20404. this._cachedTextureMatrix.m[6] = this._t2.z;
  20405. this._cachedTextureMatrix.m[8] = this._t0.x;
  20406. this._cachedTextureMatrix.m[9] = this._t0.y;
  20407. this._cachedTextureMatrix.m[10] = this._t0.z;
  20408. return this._cachedTextureMatrix;
  20409. };
  20410. Texture.prototype.getReflectionTextureMatrix = function () {
  20411. if (this.uOffset === this._cachedUOffset &&
  20412. this.vOffset === this._cachedVOffset &&
  20413. this.uScale === this._cachedUScale &&
  20414. this.vScale === this._cachedVScale &&
  20415. this.coordinatesMode === this._cachedCoordinatesMode) {
  20416. return this._cachedTextureMatrix;
  20417. }
  20418. if (!this._cachedTextureMatrix) {
  20419. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20420. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20421. }
  20422. this._cachedCoordinatesMode = this.coordinatesMode;
  20423. switch (this.coordinatesMode) {
  20424. case Texture.PLANAR_MODE:
  20425. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20426. this._cachedTextureMatrix[0] = this.uScale;
  20427. this._cachedTextureMatrix[5] = this.vScale;
  20428. this._cachedTextureMatrix[12] = this.uOffset;
  20429. this._cachedTextureMatrix[13] = this.vOffset;
  20430. break;
  20431. case Texture.PROJECTION_MODE:
  20432. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20433. this._projectionModeMatrix.m[0] = 0.5;
  20434. this._projectionModeMatrix.m[5] = -0.5;
  20435. this._projectionModeMatrix.m[10] = 0.0;
  20436. this._projectionModeMatrix.m[12] = 0.5;
  20437. this._projectionModeMatrix.m[13] = 0.5;
  20438. this._projectionModeMatrix.m[14] = 1.0;
  20439. this._projectionModeMatrix.m[15] = 1.0;
  20440. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20441. break;
  20442. default:
  20443. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20444. break;
  20445. }
  20446. return this._cachedTextureMatrix;
  20447. };
  20448. Texture.prototype.clone = function () {
  20449. var _this = this;
  20450. return BABYLON.SerializationHelper.Clone(function () {
  20451. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20452. }, this);
  20453. };
  20454. // Statics
  20455. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20456. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20457. if (onLoad === void 0) { onLoad = null; }
  20458. if (onError === void 0) { onError = null; }
  20459. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20460. };
  20461. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20462. if (parsedTexture.isCube) {
  20463. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20464. }
  20465. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20466. return null;
  20467. }
  20468. var texture = BABYLON.SerializationHelper.Parse(function () {
  20469. if (parsedTexture.mirrorPlane) {
  20470. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20471. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20472. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20473. return mirrorTexture;
  20474. }
  20475. else if (parsedTexture.isRenderTarget) {
  20476. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20477. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20478. return renderTargetTexture;
  20479. }
  20480. else {
  20481. var texture;
  20482. if (parsedTexture.base64String) {
  20483. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20484. }
  20485. else {
  20486. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20487. }
  20488. return texture;
  20489. }
  20490. }, parsedTexture, scene);
  20491. // Animations
  20492. if (parsedTexture.animations) {
  20493. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20494. var parsedAnimation = parsedTexture.animations[animationIndex];
  20495. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20496. }
  20497. }
  20498. return texture;
  20499. };
  20500. // Constants
  20501. Texture.NEAREST_SAMPLINGMODE = 1;
  20502. Texture.BILINEAR_SAMPLINGMODE = 2;
  20503. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20504. Texture.EXPLICIT_MODE = 0;
  20505. Texture.SPHERICAL_MODE = 1;
  20506. Texture.PLANAR_MODE = 2;
  20507. Texture.CUBIC_MODE = 3;
  20508. Texture.PROJECTION_MODE = 4;
  20509. Texture.SKYBOX_MODE = 5;
  20510. Texture.INVCUBIC_MODE = 6;
  20511. Texture.EQUIRECTANGULAR_MODE = 7;
  20512. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20513. Texture.CLAMP_ADDRESSMODE = 0;
  20514. Texture.WRAP_ADDRESSMODE = 1;
  20515. Texture.MIRROR_ADDRESSMODE = 2;
  20516. __decorate([
  20517. BABYLON.serialize()
  20518. ], Texture.prototype, "url", void 0);
  20519. __decorate([
  20520. BABYLON.serialize()
  20521. ], Texture.prototype, "uOffset", void 0);
  20522. __decorate([
  20523. BABYLON.serialize()
  20524. ], Texture.prototype, "vOffset", void 0);
  20525. __decorate([
  20526. BABYLON.serialize()
  20527. ], Texture.prototype, "uScale", void 0);
  20528. __decorate([
  20529. BABYLON.serialize()
  20530. ], Texture.prototype, "vScale", void 0);
  20531. __decorate([
  20532. BABYLON.serialize()
  20533. ], Texture.prototype, "uAng", void 0);
  20534. __decorate([
  20535. BABYLON.serialize()
  20536. ], Texture.prototype, "vAng", void 0);
  20537. __decorate([
  20538. BABYLON.serialize()
  20539. ], Texture.prototype, "wAng", void 0);
  20540. return Texture;
  20541. })(BABYLON.BaseTexture);
  20542. BABYLON.Texture = Texture;
  20543. })(BABYLON || (BABYLON = {}));
  20544. var BABYLON;
  20545. (function (BABYLON) {
  20546. var CubeTexture = (function (_super) {
  20547. __extends(CubeTexture, _super);
  20548. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20549. _super.call(this, scene);
  20550. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20551. this.name = rootUrl;
  20552. this.url = rootUrl;
  20553. this._noMipmap = noMipmap;
  20554. this.hasAlpha = false;
  20555. if (!rootUrl && !files) {
  20556. return;
  20557. }
  20558. this._texture = this._getFromCache(rootUrl, noMipmap);
  20559. if (!files) {
  20560. if (!extensions) {
  20561. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20562. }
  20563. files = [];
  20564. for (var index = 0; index < extensions.length; index++) {
  20565. files.push(rootUrl + extensions[index]);
  20566. }
  20567. this._extensions = extensions;
  20568. }
  20569. this._files = files;
  20570. if (!this._texture) {
  20571. if (!scene.useDelayedTextureLoading) {
  20572. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20573. }
  20574. else {
  20575. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20576. }
  20577. }
  20578. this.isCube = true;
  20579. this._textureMatrix = BABYLON.Matrix.Identity();
  20580. }
  20581. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20582. return new CubeTexture("", scene, null, noMipmap, files);
  20583. };
  20584. // Methods
  20585. CubeTexture.prototype.delayLoad = function () {
  20586. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20587. return;
  20588. }
  20589. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20590. this._texture = this._getFromCache(this.url, this._noMipmap);
  20591. if (!this._texture) {
  20592. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20593. }
  20594. };
  20595. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20596. return this._textureMatrix;
  20597. };
  20598. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20599. var texture = BABYLON.SerializationHelper.Parse(function () {
  20600. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20601. }, parsedTexture, scene);
  20602. // Animations
  20603. if (parsedTexture.animations) {
  20604. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20605. var parsedAnimation = parsedTexture.animations[animationIndex];
  20606. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20607. }
  20608. }
  20609. return texture;
  20610. };
  20611. CubeTexture.prototype.clone = function () {
  20612. var _this = this;
  20613. return BABYLON.SerializationHelper.Clone(function () {
  20614. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20615. }, this);
  20616. };
  20617. return CubeTexture;
  20618. })(BABYLON.BaseTexture);
  20619. BABYLON.CubeTexture = CubeTexture;
  20620. })(BABYLON || (BABYLON = {}));
  20621. var BABYLON;
  20622. (function (BABYLON) {
  20623. var RenderTargetTexture = (function (_super) {
  20624. __extends(RenderTargetTexture, _super);
  20625. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20626. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20627. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20628. if (isCube === void 0) { isCube = false; }
  20629. _super.call(this, null, scene, !generateMipMaps);
  20630. this.isCube = isCube;
  20631. this.renderList = new Array();
  20632. this.renderParticles = true;
  20633. this.renderSprites = false;
  20634. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20635. this._currentRefreshId = -1;
  20636. this._refreshRate = 1;
  20637. this.name = name;
  20638. this.isRenderTarget = true;
  20639. this._size = size;
  20640. this._generateMipMaps = generateMipMaps;
  20641. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20642. if (isCube) {
  20643. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20644. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20645. this._textureMatrix = BABYLON.Matrix.Identity();
  20646. }
  20647. else {
  20648. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20649. }
  20650. // Rendering groups
  20651. this._renderingManager = new BABYLON.RenderingManager(scene);
  20652. }
  20653. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20654. get: function () {
  20655. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20656. },
  20657. enumerable: true,
  20658. configurable: true
  20659. });
  20660. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20661. get: function () {
  20662. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20663. },
  20664. enumerable: true,
  20665. configurable: true
  20666. });
  20667. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20668. get: function () {
  20669. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20670. },
  20671. enumerable: true,
  20672. configurable: true
  20673. });
  20674. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20675. this._currentRefreshId = -1;
  20676. };
  20677. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20678. get: function () {
  20679. return this._refreshRate;
  20680. },
  20681. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20682. set: function (value) {
  20683. this._refreshRate = value;
  20684. this.resetRefreshCounter();
  20685. },
  20686. enumerable: true,
  20687. configurable: true
  20688. });
  20689. RenderTargetTexture.prototype._shouldRender = function () {
  20690. if (this._currentRefreshId === -1) {
  20691. this._currentRefreshId = 1;
  20692. return true;
  20693. }
  20694. if (this.refreshRate === this._currentRefreshId) {
  20695. this._currentRefreshId = 1;
  20696. return true;
  20697. }
  20698. this._currentRefreshId++;
  20699. return false;
  20700. };
  20701. RenderTargetTexture.prototype.isReady = function () {
  20702. if (!this.getScene().renderTargetsEnabled) {
  20703. return false;
  20704. }
  20705. return _super.prototype.isReady.call(this);
  20706. };
  20707. RenderTargetTexture.prototype.getRenderSize = function () {
  20708. return this._size;
  20709. };
  20710. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20711. get: function () {
  20712. return true;
  20713. },
  20714. enumerable: true,
  20715. configurable: true
  20716. });
  20717. RenderTargetTexture.prototype.scale = function (ratio) {
  20718. var newSize = this._size * ratio;
  20719. this.resize(newSize, this._generateMipMaps);
  20720. };
  20721. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20722. if (this.isCube) {
  20723. return this._textureMatrix;
  20724. }
  20725. return _super.prototype.getReflectionTextureMatrix.call(this);
  20726. };
  20727. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20728. this.releaseInternalTexture();
  20729. if (this.isCube) {
  20730. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20731. }
  20732. else {
  20733. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20734. }
  20735. };
  20736. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20737. var scene = this.getScene();
  20738. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20739. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20740. }
  20741. if (this._waitingRenderList) {
  20742. this.renderList = [];
  20743. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20744. var id = this._waitingRenderList[index];
  20745. this.renderList.push(scene.getMeshByID(id));
  20746. }
  20747. delete this._waitingRenderList;
  20748. }
  20749. if (this.renderList && this.renderList.length === 0) {
  20750. return;
  20751. }
  20752. // Prepare renderingManager
  20753. this._renderingManager.reset();
  20754. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20755. var sceneRenderId = scene.getRenderId();
  20756. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20757. var mesh = currentRenderList[meshIndex];
  20758. if (mesh) {
  20759. if (!mesh.isReady()) {
  20760. // Reset _currentRefreshId
  20761. this.resetRefreshCounter();
  20762. continue;
  20763. }
  20764. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20765. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20766. mesh._activate(sceneRenderId);
  20767. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20768. var subMesh = mesh.subMeshes[subIndex];
  20769. scene._activeIndices += subMesh.indexCount;
  20770. this._renderingManager.dispatch(subMesh);
  20771. }
  20772. }
  20773. }
  20774. }
  20775. if (this.isCube) {
  20776. for (var face = 0; face < 6; face++) {
  20777. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20778. scene.incrementRenderId();
  20779. scene.resetCachedMaterial();
  20780. }
  20781. }
  20782. else {
  20783. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20784. }
  20785. if (this.onAfterUnbind) {
  20786. this.onAfterUnbind();
  20787. }
  20788. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20789. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20790. }
  20791. scene.resetCachedMaterial();
  20792. };
  20793. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20794. var scene = this.getScene();
  20795. var engine = scene.getEngine();
  20796. // Bind
  20797. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20798. if (this.isCube) {
  20799. engine.bindFramebuffer(this._texture, faceIndex);
  20800. }
  20801. else {
  20802. engine.bindFramebuffer(this._texture);
  20803. }
  20804. }
  20805. if (this.onBeforeRender) {
  20806. this.onBeforeRender(faceIndex);
  20807. }
  20808. // Clear
  20809. if (this.onClear) {
  20810. this.onClear(engine);
  20811. }
  20812. else {
  20813. engine.clear(scene.clearColor, true, true);
  20814. }
  20815. if (!this._doNotChangeAspectRatio) {
  20816. scene.updateTransformMatrix(true);
  20817. }
  20818. // Render
  20819. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20820. if (useCameraPostProcess) {
  20821. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20822. }
  20823. if (!this._doNotChangeAspectRatio) {
  20824. scene.updateTransformMatrix(true);
  20825. }
  20826. if (this.onAfterRender) {
  20827. this.onAfterRender(faceIndex);
  20828. }
  20829. // Dump ?
  20830. if (dumpForDebug) {
  20831. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20832. }
  20833. // Unbind
  20834. if (!this.isCube || faceIndex === 5) {
  20835. if (this.isCube) {
  20836. if (faceIndex === 5) {
  20837. engine.generateMipMapsForCubemap(this._texture);
  20838. }
  20839. }
  20840. engine.unBindFramebuffer(this._texture, this.isCube);
  20841. }
  20842. };
  20843. RenderTargetTexture.prototype.clone = function () {
  20844. var textureSize = this.getSize();
  20845. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20846. // Base texture
  20847. newTexture.hasAlpha = this.hasAlpha;
  20848. newTexture.level = this.level;
  20849. // RenderTarget Texture
  20850. newTexture.coordinatesMode = this.coordinatesMode;
  20851. newTexture.renderList = this.renderList.slice(0);
  20852. return newTexture;
  20853. };
  20854. RenderTargetTexture.prototype.serialize = function () {
  20855. if (!this.name) {
  20856. return null;
  20857. }
  20858. var serializationObject = _super.prototype.serialize.call(this);
  20859. serializationObject.renderTargetSize = this.getRenderSize();
  20860. serializationObject.renderList = [];
  20861. for (var index = 0; index < this.renderList.length; index++) {
  20862. serializationObject.renderList.push(this.renderList[index].id);
  20863. }
  20864. return serializationObject;
  20865. };
  20866. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  20867. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  20868. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  20869. return RenderTargetTexture;
  20870. })(BABYLON.Texture);
  20871. BABYLON.RenderTargetTexture = RenderTargetTexture;
  20872. })(BABYLON || (BABYLON = {}));
  20873. var BABYLON;
  20874. (function (BABYLON) {
  20875. var ProceduralTexture = (function (_super) {
  20876. __extends(ProceduralTexture, _super);
  20877. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  20878. if (generateMipMaps === void 0) { generateMipMaps = true; }
  20879. if (isCube === void 0) { isCube = false; }
  20880. _super.call(this, null, scene, !generateMipMaps);
  20881. this.isCube = isCube;
  20882. this.isEnabled = true;
  20883. this._currentRefreshId = -1;
  20884. this._refreshRate = 1;
  20885. this._vertexDeclaration = [2];
  20886. this._vertexStrideSize = 2 * 4;
  20887. this._uniforms = new Array();
  20888. this._samplers = new Array();
  20889. this._textures = new Array();
  20890. this._floats = new Array();
  20891. this._floatsArrays = {};
  20892. this._colors3 = new Array();
  20893. this._colors4 = new Array();
  20894. this._vectors2 = new Array();
  20895. this._vectors3 = new Array();
  20896. this._matrices = new Array();
  20897. this._fallbackTextureUsed = false;
  20898. scene._proceduralTextures.push(this);
  20899. this.name = name;
  20900. this.isRenderTarget = true;
  20901. this._size = size;
  20902. this._generateMipMaps = generateMipMaps;
  20903. this.setFragment(fragment);
  20904. this._fallbackTexture = fallbackTexture;
  20905. if (isCube) {
  20906. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20907. this.setFloat("face", 0);
  20908. }
  20909. else {
  20910. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  20911. }
  20912. // VBO
  20913. var vertices = [];
  20914. vertices.push(1, 1);
  20915. vertices.push(-1, 1);
  20916. vertices.push(-1, -1);
  20917. vertices.push(1, -1);
  20918. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20919. // Indices
  20920. var indices = [];
  20921. indices.push(0);
  20922. indices.push(1);
  20923. indices.push(2);
  20924. indices.push(0);
  20925. indices.push(2);
  20926. indices.push(3);
  20927. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20928. }
  20929. ProceduralTexture.prototype.reset = function () {
  20930. if (this._effect === undefined) {
  20931. return;
  20932. }
  20933. var engine = this.getScene().getEngine();
  20934. engine._releaseEffect(this._effect);
  20935. };
  20936. ProceduralTexture.prototype.isReady = function () {
  20937. var _this = this;
  20938. var engine = this.getScene().getEngine();
  20939. var shaders;
  20940. if (!this._fragment) {
  20941. return false;
  20942. }
  20943. if (this._fallbackTextureUsed) {
  20944. return true;
  20945. }
  20946. if (this._fragment.fragmentElement !== undefined) {
  20947. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  20948. }
  20949. else {
  20950. shaders = { vertex: "procedural", fragment: this._fragment };
  20951. }
  20952. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  20953. _this.releaseInternalTexture();
  20954. if (_this._fallbackTexture) {
  20955. _this._texture = _this._fallbackTexture._texture;
  20956. _this._texture.references++;
  20957. }
  20958. _this._fallbackTextureUsed = true;
  20959. });
  20960. return this._effect.isReady();
  20961. };
  20962. ProceduralTexture.prototype.resetRefreshCounter = function () {
  20963. this._currentRefreshId = -1;
  20964. };
  20965. ProceduralTexture.prototype.setFragment = function (fragment) {
  20966. this._fragment = fragment;
  20967. };
  20968. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  20969. get: function () {
  20970. return this._refreshRate;
  20971. },
  20972. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20973. set: function (value) {
  20974. this._refreshRate = value;
  20975. this.resetRefreshCounter();
  20976. },
  20977. enumerable: true,
  20978. configurable: true
  20979. });
  20980. ProceduralTexture.prototype._shouldRender = function () {
  20981. if (!this.isEnabled || !this.isReady() || !this._texture) {
  20982. return false;
  20983. }
  20984. if (this._fallbackTextureUsed) {
  20985. return false;
  20986. }
  20987. if (this._currentRefreshId === -1) {
  20988. this._currentRefreshId = 1;
  20989. return true;
  20990. }
  20991. if (this.refreshRate === this._currentRefreshId) {
  20992. this._currentRefreshId = 1;
  20993. return true;
  20994. }
  20995. this._currentRefreshId++;
  20996. return false;
  20997. };
  20998. ProceduralTexture.prototype.getRenderSize = function () {
  20999. return this._size;
  21000. };
  21001. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21002. if (this._fallbackTextureUsed) {
  21003. return;
  21004. }
  21005. this.releaseInternalTexture();
  21006. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21007. };
  21008. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21009. if (this._uniforms.indexOf(uniformName) === -1) {
  21010. this._uniforms.push(uniformName);
  21011. }
  21012. };
  21013. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21014. if (this._samplers.indexOf(name) === -1) {
  21015. this._samplers.push(name);
  21016. }
  21017. this._textures[name] = texture;
  21018. return this;
  21019. };
  21020. ProceduralTexture.prototype.setFloat = function (name, value) {
  21021. this._checkUniform(name);
  21022. this._floats[name] = value;
  21023. return this;
  21024. };
  21025. ProceduralTexture.prototype.setFloats = function (name, value) {
  21026. this._checkUniform(name);
  21027. this._floatsArrays[name] = value;
  21028. return this;
  21029. };
  21030. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21031. this._checkUniform(name);
  21032. this._colors3[name] = value;
  21033. return this;
  21034. };
  21035. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21036. this._checkUniform(name);
  21037. this._colors4[name] = value;
  21038. return this;
  21039. };
  21040. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21041. this._checkUniform(name);
  21042. this._vectors2[name] = value;
  21043. return this;
  21044. };
  21045. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21046. this._checkUniform(name);
  21047. this._vectors3[name] = value;
  21048. return this;
  21049. };
  21050. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21051. this._checkUniform(name);
  21052. this._matrices[name] = value;
  21053. return this;
  21054. };
  21055. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21056. var scene = this.getScene();
  21057. var engine = scene.getEngine();
  21058. // Render
  21059. engine.enableEffect(this._effect);
  21060. engine.setState(false);
  21061. // Texture
  21062. for (var name in this._textures) {
  21063. this._effect.setTexture(name, this._textures[name]);
  21064. }
  21065. // Float
  21066. for (name in this._floats) {
  21067. this._effect.setFloat(name, this._floats[name]);
  21068. }
  21069. // Floats
  21070. for (name in this._floatsArrays) {
  21071. this._effect.setArray(name, this._floatsArrays[name]);
  21072. }
  21073. // Color3
  21074. for (name in this._colors3) {
  21075. this._effect.setColor3(name, this._colors3[name]);
  21076. }
  21077. // Color4
  21078. for (name in this._colors4) {
  21079. var color = this._colors4[name];
  21080. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21081. }
  21082. // Vector2
  21083. for (name in this._vectors2) {
  21084. this._effect.setVector2(name, this._vectors2[name]);
  21085. }
  21086. // Vector3
  21087. for (name in this._vectors3) {
  21088. this._effect.setVector3(name, this._vectors3[name]);
  21089. }
  21090. // Matrix
  21091. for (name in this._matrices) {
  21092. this._effect.setMatrix(name, this._matrices[name]);
  21093. }
  21094. // VBOs
  21095. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21096. if (this.isCube) {
  21097. for (var face = 0; face < 6; face++) {
  21098. engine.bindFramebuffer(this._texture, face);
  21099. this._effect.setFloat("face", face);
  21100. // Clear
  21101. engine.clear(scene.clearColor, true, true);
  21102. // Draw order
  21103. engine.draw(true, 0, 6);
  21104. // Mipmaps
  21105. if (face === 5) {
  21106. engine.generateMipMapsForCubemap(this._texture);
  21107. }
  21108. }
  21109. }
  21110. else {
  21111. engine.bindFramebuffer(this._texture);
  21112. // Clear
  21113. engine.clear(scene.clearColor, true, true);
  21114. // Draw order
  21115. engine.draw(true, 0, 6);
  21116. }
  21117. // Unbind
  21118. engine.unBindFramebuffer(this._texture, this.isCube);
  21119. if (this.onGenerated) {
  21120. this.onGenerated();
  21121. }
  21122. };
  21123. ProceduralTexture.prototype.clone = function () {
  21124. var textureSize = this.getSize();
  21125. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21126. // Base texture
  21127. newTexture.hasAlpha = this.hasAlpha;
  21128. newTexture.level = this.level;
  21129. // RenderTarget Texture
  21130. newTexture.coordinatesMode = this.coordinatesMode;
  21131. return newTexture;
  21132. };
  21133. ProceduralTexture.prototype.dispose = function () {
  21134. var index = this.getScene()._proceduralTextures.indexOf(this);
  21135. if (index >= 0) {
  21136. this.getScene()._proceduralTextures.splice(index, 1);
  21137. }
  21138. _super.prototype.dispose.call(this);
  21139. };
  21140. return ProceduralTexture;
  21141. })(BABYLON.Texture);
  21142. BABYLON.ProceduralTexture = ProceduralTexture;
  21143. })(BABYLON || (BABYLON = {}));
  21144. var BABYLON;
  21145. (function (BABYLON) {
  21146. var MirrorTexture = (function (_super) {
  21147. __extends(MirrorTexture, _super);
  21148. function MirrorTexture(name, size, scene, generateMipMaps) {
  21149. var _this = this;
  21150. _super.call(this, name, size, scene, generateMipMaps, true);
  21151. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21152. this._transformMatrix = BABYLON.Matrix.Zero();
  21153. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21154. this.onBeforeRender = function () {
  21155. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21156. _this._savedViewMatrix = scene.getViewMatrix();
  21157. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21158. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21159. scene.clipPlane = _this.mirrorPlane;
  21160. scene.getEngine().cullBackFaces = false;
  21161. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21162. };
  21163. this.onAfterRender = function () {
  21164. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21165. scene.getEngine().cullBackFaces = true;
  21166. scene._mirroredCameraPosition = null;
  21167. delete scene.clipPlane;
  21168. };
  21169. }
  21170. MirrorTexture.prototype.clone = function () {
  21171. var textureSize = this.getSize();
  21172. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21173. // Base texture
  21174. newTexture.hasAlpha = this.hasAlpha;
  21175. newTexture.level = this.level;
  21176. // Mirror Texture
  21177. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21178. newTexture.renderList = this.renderList.slice(0);
  21179. return newTexture;
  21180. };
  21181. MirrorTexture.prototype.serialize = function () {
  21182. if (!this.name) {
  21183. return null;
  21184. }
  21185. var serializationObject = _super.prototype.serialize.call(this);
  21186. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21187. return serializationObject;
  21188. };
  21189. return MirrorTexture;
  21190. })(BABYLON.RenderTargetTexture);
  21191. BABYLON.MirrorTexture = MirrorTexture;
  21192. })(BABYLON || (BABYLON = {}));
  21193. var BABYLON;
  21194. (function (BABYLON) {
  21195. /**
  21196. * Creates a refraction texture used by refraction channel of the standard material.
  21197. * @param name the texture name
  21198. * @param size size of the underlying texture
  21199. * @param scene root scene
  21200. */
  21201. var RefractionTexture = (function (_super) {
  21202. __extends(RefractionTexture, _super);
  21203. function RefractionTexture(name, size, scene, generateMipMaps) {
  21204. var _this = this;
  21205. _super.call(this, name, size, scene, generateMipMaps, true);
  21206. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21207. this.depth = 2.0;
  21208. this.onBeforeRender = function () {
  21209. scene.clipPlane = _this.refractionPlane;
  21210. };
  21211. this.onAfterRender = function () {
  21212. delete scene.clipPlane;
  21213. };
  21214. }
  21215. RefractionTexture.prototype.clone = function () {
  21216. var textureSize = this.getSize();
  21217. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21218. // Base texture
  21219. newTexture.hasAlpha = this.hasAlpha;
  21220. newTexture.level = this.level;
  21221. // Refraction Texture
  21222. newTexture.refractionPlane = this.refractionPlane.clone();
  21223. newTexture.renderList = this.renderList.slice(0);
  21224. newTexture.depth = this.depth;
  21225. return newTexture;
  21226. };
  21227. RefractionTexture.prototype.serialize = function () {
  21228. if (!this.name) {
  21229. return null;
  21230. }
  21231. var serializationObject = _super.prototype.serialize.call(this);
  21232. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21233. serializationObject.depth = this.depth;
  21234. return serializationObject;
  21235. };
  21236. return RefractionTexture;
  21237. })(BABYLON.RenderTargetTexture);
  21238. BABYLON.RefractionTexture = RefractionTexture;
  21239. })(BABYLON || (BABYLON = {}));
  21240. var BABYLON;
  21241. (function (BABYLON) {
  21242. var DynamicTexture = (function (_super) {
  21243. __extends(DynamicTexture, _super);
  21244. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21246. _super.call(this, null, scene, !generateMipMaps);
  21247. this.name = name;
  21248. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21249. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21250. this._generateMipMaps = generateMipMaps;
  21251. if (options.getContext) {
  21252. this._canvas = options;
  21253. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21254. }
  21255. else {
  21256. this._canvas = document.createElement("canvas");
  21257. if (options.width) {
  21258. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21259. }
  21260. else {
  21261. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21262. }
  21263. }
  21264. var textureSize = this.getSize();
  21265. this._canvas.width = textureSize.width;
  21266. this._canvas.height = textureSize.height;
  21267. this._context = this._canvas.getContext("2d");
  21268. }
  21269. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21270. get: function () {
  21271. return true;
  21272. },
  21273. enumerable: true,
  21274. configurable: true
  21275. });
  21276. DynamicTexture.prototype.scale = function (ratio) {
  21277. var textureSize = this.getSize();
  21278. textureSize.width *= ratio;
  21279. textureSize.height *= ratio;
  21280. this._canvas.width = textureSize.width;
  21281. this._canvas.height = textureSize.height;
  21282. this.releaseInternalTexture();
  21283. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21284. };
  21285. DynamicTexture.prototype.getContext = function () {
  21286. return this._context;
  21287. };
  21288. DynamicTexture.prototype.clear = function () {
  21289. var size = this.getSize();
  21290. this._context.fillRect(0, 0, size.width, size.height);
  21291. };
  21292. DynamicTexture.prototype.update = function (invertY) {
  21293. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21294. };
  21295. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21296. if (update === void 0) { update = true; }
  21297. var size = this.getSize();
  21298. if (clearColor) {
  21299. this._context.fillStyle = clearColor;
  21300. this._context.fillRect(0, 0, size.width, size.height);
  21301. }
  21302. this._context.font = font;
  21303. if (x === null) {
  21304. var textSize = this._context.measureText(text);
  21305. x = (size.width - textSize.width) / 2;
  21306. }
  21307. this._context.fillStyle = color;
  21308. this._context.fillText(text, x, y);
  21309. if (update) {
  21310. this.update(invertY);
  21311. }
  21312. };
  21313. DynamicTexture.prototype.clone = function () {
  21314. var textureSize = this.getSize();
  21315. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21316. // Base texture
  21317. newTexture.hasAlpha = this.hasAlpha;
  21318. newTexture.level = this.level;
  21319. // Dynamic Texture
  21320. newTexture.wrapU = this.wrapU;
  21321. newTexture.wrapV = this.wrapV;
  21322. return newTexture;
  21323. };
  21324. return DynamicTexture;
  21325. })(BABYLON.Texture);
  21326. BABYLON.DynamicTexture = DynamicTexture;
  21327. })(BABYLON || (BABYLON = {}));
  21328. var BABYLON;
  21329. (function (BABYLON) {
  21330. var VideoTexture = (function (_super) {
  21331. __extends(VideoTexture, _super);
  21332. /**
  21333. * Creates a video texture.
  21334. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21335. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21336. * @param {BABYLON.Scene} scene is obviously the current scene.
  21337. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21338. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21339. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21340. */
  21341. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21342. var _this = this;
  21343. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21344. if (invertY === void 0) { invertY = false; }
  21345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21346. _super.call(this, null, scene, !generateMipMaps, invertY);
  21347. this._autoLaunch = true;
  21348. var urls;
  21349. this.name = name;
  21350. if (urlsOrVideo instanceof HTMLVideoElement) {
  21351. this.video = urlsOrVideo;
  21352. }
  21353. else {
  21354. urls = urlsOrVideo;
  21355. this.video = document.createElement("video");
  21356. this.video.autoplay = false;
  21357. this.video.loop = true;
  21358. }
  21359. this._generateMipMaps = generateMipMaps;
  21360. this._samplingMode = samplingMode;
  21361. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21362. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21363. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21364. }
  21365. else {
  21366. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21367. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21368. this._generateMipMaps = false;
  21369. }
  21370. if (urls) {
  21371. this.video.addEventListener("canplaythrough", function () {
  21372. _this._createTexture();
  21373. });
  21374. urls.forEach(function (url) {
  21375. var source = document.createElement("source");
  21376. source.src = url;
  21377. _this.video.appendChild(source);
  21378. });
  21379. }
  21380. else {
  21381. this._createTexture();
  21382. }
  21383. this._lastUpdate = BABYLON.Tools.Now;
  21384. }
  21385. VideoTexture.prototype._createTexture = function () {
  21386. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21387. this._texture.isReady = true;
  21388. };
  21389. VideoTexture.prototype.update = function () {
  21390. if (this._autoLaunch) {
  21391. this._autoLaunch = false;
  21392. this.video.play();
  21393. }
  21394. var now = BABYLON.Tools.Now;
  21395. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21396. return false;
  21397. }
  21398. this._lastUpdate = now;
  21399. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21400. return true;
  21401. };
  21402. return VideoTexture;
  21403. })(BABYLON.Texture);
  21404. BABYLON.VideoTexture = VideoTexture;
  21405. })(BABYLON || (BABYLON = {}));
  21406. var BABYLON;
  21407. (function (BABYLON) {
  21408. var CustomProceduralTexture = (function (_super) {
  21409. __extends(CustomProceduralTexture, _super);
  21410. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21411. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21412. this._animate = true;
  21413. this._time = 0;
  21414. this._texturePath = texturePath;
  21415. //Try to load json
  21416. this.loadJson(texturePath);
  21417. this.refreshRate = 1;
  21418. }
  21419. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21420. var _this = this;
  21421. var that = this;
  21422. function noConfigFile() {
  21423. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21424. try {
  21425. that.setFragment(that._texturePath);
  21426. }
  21427. catch (ex) {
  21428. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21429. }
  21430. }
  21431. var configFileUrl = jsonUrl + "/config.json";
  21432. var xhr = new XMLHttpRequest();
  21433. xhr.open("GET", configFileUrl, true);
  21434. xhr.addEventListener("load", function () {
  21435. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21436. try {
  21437. _this._config = JSON.parse(xhr.response);
  21438. _this.updateShaderUniforms();
  21439. _this.updateTextures();
  21440. _this.setFragment(_this._texturePath + "/custom");
  21441. _this._animate = _this._config.animate;
  21442. _this.refreshRate = _this._config.refreshrate;
  21443. }
  21444. catch (ex) {
  21445. noConfigFile();
  21446. }
  21447. }
  21448. else {
  21449. noConfigFile();
  21450. }
  21451. }, false);
  21452. xhr.addEventListener("error", function () {
  21453. noConfigFile();
  21454. }, false);
  21455. try {
  21456. xhr.send();
  21457. }
  21458. catch (ex) {
  21459. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21460. }
  21461. };
  21462. CustomProceduralTexture.prototype.isReady = function () {
  21463. if (!_super.prototype.isReady.call(this)) {
  21464. return false;
  21465. }
  21466. for (var name in this._textures) {
  21467. var texture = this._textures[name];
  21468. if (!texture.isReady()) {
  21469. return false;
  21470. }
  21471. }
  21472. return true;
  21473. };
  21474. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21475. if (this._animate) {
  21476. this._time += this.getScene().getAnimationRatio() * 0.03;
  21477. this.updateShaderUniforms();
  21478. }
  21479. _super.prototype.render.call(this, useCameraPostProcess);
  21480. };
  21481. CustomProceduralTexture.prototype.updateTextures = function () {
  21482. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21483. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21484. }
  21485. };
  21486. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21487. if (this._config) {
  21488. for (var j = 0; j < this._config.uniforms.length; j++) {
  21489. var uniform = this._config.uniforms[j];
  21490. switch (uniform.type) {
  21491. case "float":
  21492. this.setFloat(uniform.name, uniform.value);
  21493. break;
  21494. case "color3":
  21495. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21496. break;
  21497. case "color4":
  21498. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21499. break;
  21500. case "vector2":
  21501. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21502. break;
  21503. case "vector3":
  21504. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21505. break;
  21506. }
  21507. }
  21508. }
  21509. this.setFloat("time", this._time);
  21510. };
  21511. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21512. get: function () {
  21513. return this._animate;
  21514. },
  21515. set: function (value) {
  21516. this._animate = value;
  21517. },
  21518. enumerable: true,
  21519. configurable: true
  21520. });
  21521. return CustomProceduralTexture;
  21522. })(BABYLON.ProceduralTexture);
  21523. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21524. })(BABYLON || (BABYLON = {}));
  21525. var BABYLON;
  21526. (function (BABYLON) {
  21527. var EffectFallbacks = (function () {
  21528. function EffectFallbacks() {
  21529. this._defines = {};
  21530. this._currentRank = 32;
  21531. this._maxRank = -1;
  21532. }
  21533. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21534. if (!this._defines[rank]) {
  21535. if (rank < this._currentRank) {
  21536. this._currentRank = rank;
  21537. }
  21538. if (rank > this._maxRank) {
  21539. this._maxRank = rank;
  21540. }
  21541. this._defines[rank] = new Array();
  21542. }
  21543. this._defines[rank].push(define);
  21544. };
  21545. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21546. this._meshRank = rank;
  21547. this._mesh = mesh;
  21548. if (rank > this._maxRank) {
  21549. this._maxRank = rank;
  21550. }
  21551. };
  21552. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21553. get: function () {
  21554. return this._currentRank <= this._maxRank;
  21555. },
  21556. enumerable: true,
  21557. configurable: true
  21558. });
  21559. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21560. var currentFallbacks = this._defines[this._currentRank];
  21561. for (var index = 0; index < currentFallbacks.length; index++) {
  21562. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21563. }
  21564. if (this._mesh && this._currentRank === this._meshRank) {
  21565. this._mesh.computeBonesUsingShaders = false;
  21566. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21567. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21568. }
  21569. this._currentRank++;
  21570. return currentDefines;
  21571. };
  21572. return EffectFallbacks;
  21573. })();
  21574. BABYLON.EffectFallbacks = EffectFallbacks;
  21575. var Effect = (function () {
  21576. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  21577. var _this = this;
  21578. this._isReady = false;
  21579. this._compilationError = "";
  21580. this._valueCache = [];
  21581. this._engine = engine;
  21582. this.name = baseName;
  21583. this.defines = defines;
  21584. this._uniformsNames = uniformsNames.concat(samplers);
  21585. this._samplers = samplers;
  21586. this._attributesNames = attributesNames;
  21587. this.onError = onError;
  21588. this.onCompiled = onCompiled;
  21589. var vertexSource;
  21590. var fragmentSource;
  21591. if (baseName.vertexElement) {
  21592. vertexSource = document.getElementById(baseName.vertexElement);
  21593. if (!vertexSource) {
  21594. vertexSource = baseName.vertexElement;
  21595. }
  21596. }
  21597. else {
  21598. vertexSource = baseName.vertex || baseName;
  21599. }
  21600. if (baseName.fragmentElement) {
  21601. fragmentSource = document.getElementById(baseName.fragmentElement);
  21602. if (!fragmentSource) {
  21603. fragmentSource = baseName.fragmentElement;
  21604. }
  21605. }
  21606. else {
  21607. fragmentSource = baseName.fragment || baseName;
  21608. }
  21609. this._loadVertexShader(vertexSource, function (vertexCode) {
  21610. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21611. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21612. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21613. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21614. });
  21615. });
  21616. });
  21617. });
  21618. }
  21619. // Properties
  21620. Effect.prototype.isReady = function () {
  21621. return this._isReady;
  21622. };
  21623. Effect.prototype.getProgram = function () {
  21624. return this._program;
  21625. };
  21626. Effect.prototype.getAttributesNames = function () {
  21627. return this._attributesNames;
  21628. };
  21629. Effect.prototype.getAttributeLocation = function (index) {
  21630. return this._attributes[index];
  21631. };
  21632. Effect.prototype.getAttributeLocationByName = function (name) {
  21633. var index = this._attributesNames.indexOf(name);
  21634. return this._attributes[index];
  21635. };
  21636. Effect.prototype.getAttributesCount = function () {
  21637. return this._attributes.length;
  21638. };
  21639. Effect.prototype.getUniformIndex = function (uniformName) {
  21640. return this._uniformsNames.indexOf(uniformName);
  21641. };
  21642. Effect.prototype.getUniform = function (uniformName) {
  21643. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21644. };
  21645. Effect.prototype.getSamplers = function () {
  21646. return this._samplers;
  21647. };
  21648. Effect.prototype.getCompilationError = function () {
  21649. return this._compilationError;
  21650. };
  21651. // Methods
  21652. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21653. // DOM element ?
  21654. if (vertex instanceof HTMLElement) {
  21655. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21656. callback(vertexCode);
  21657. return;
  21658. }
  21659. // Is in local store ?
  21660. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21661. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21662. return;
  21663. }
  21664. var vertexShaderUrl;
  21665. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21666. vertexShaderUrl = vertex;
  21667. }
  21668. else {
  21669. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21670. }
  21671. // Vertex shader
  21672. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21673. };
  21674. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21675. // DOM element ?
  21676. if (fragment instanceof HTMLElement) {
  21677. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21678. callback(fragmentCode);
  21679. return;
  21680. }
  21681. // Is in local store ?
  21682. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21683. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21684. return;
  21685. }
  21686. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21687. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21688. return;
  21689. }
  21690. var fragmentShaderUrl;
  21691. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21692. fragmentShaderUrl = fragment;
  21693. }
  21694. else {
  21695. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21696. }
  21697. // Fragment shader
  21698. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21699. };
  21700. Effect.prototype._dumpShadersName = function () {
  21701. if (this.name.vertexElement) {
  21702. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21703. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21704. }
  21705. else if (this.name.vertex) {
  21706. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21707. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21708. }
  21709. else {
  21710. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21711. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21712. }
  21713. };
  21714. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21715. var _this = this;
  21716. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21717. var match = regex.exec(sourceCode);
  21718. var returnValue = new String(sourceCode);
  21719. while (match != null) {
  21720. var includeFile = match[1];
  21721. if (Effect.IncludesShadersStore[includeFile]) {
  21722. // Substitution
  21723. var includeContent = Effect.IncludesShadersStore[includeFile];
  21724. if (match[2]) {
  21725. var splits = match[3].split(",");
  21726. for (var index = 0; index < splits.length; index += 2) {
  21727. var source = new RegExp(splits[index], "g");
  21728. var dest = splits[index + 1];
  21729. includeContent = includeContent.replace(source, dest);
  21730. }
  21731. }
  21732. if (match[4]) {
  21733. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  21734. }
  21735. // Replace
  21736. returnValue = returnValue.replace(match[0], includeContent);
  21737. }
  21738. else {
  21739. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21740. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21741. Effect.IncludesShadersStore[includeFile] = fileContent;
  21742. _this._processIncludes(returnValue, callback);
  21743. });
  21744. return;
  21745. }
  21746. match = regex.exec(sourceCode);
  21747. }
  21748. callback(returnValue);
  21749. };
  21750. Effect.prototype._processPrecision = function (source) {
  21751. if (source.indexOf("precision highp float") === -1) {
  21752. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21753. source = "precision mediump float;\n" + source;
  21754. }
  21755. else {
  21756. source = "precision highp float;\n" + source;
  21757. }
  21758. }
  21759. else {
  21760. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21761. source = source.replace("precision highp float", "precision mediump float");
  21762. }
  21763. }
  21764. return source;
  21765. };
  21766. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21767. try {
  21768. var engine = this._engine;
  21769. // Precision
  21770. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21771. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21772. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21773. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21774. this._attributes = engine.getAttributes(this._program, attributesNames);
  21775. for (var index = 0; index < this._samplers.length; index++) {
  21776. var sampler = this.getUniform(this._samplers[index]);
  21777. if (sampler == null) {
  21778. this._samplers.splice(index, 1);
  21779. index--;
  21780. }
  21781. }
  21782. engine.bindSamplers(this);
  21783. this._isReady = true;
  21784. if (this.onCompiled) {
  21785. this.onCompiled(this);
  21786. }
  21787. }
  21788. catch (e) {
  21789. // Is it a problem with precision?
  21790. if (e.message.indexOf("highp") !== -1) {
  21791. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21792. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21793. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21794. return;
  21795. }
  21796. // Let's go through fallbacks then
  21797. if (fallbacks && fallbacks.isMoreFallbacks) {
  21798. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21799. this._dumpShadersName();
  21800. defines = fallbacks.reduce(defines);
  21801. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21802. }
  21803. else {
  21804. BABYLON.Tools.Error("Unable to compile effect: ");
  21805. this._dumpShadersName();
  21806. BABYLON.Tools.Error("Defines: " + defines);
  21807. BABYLON.Tools.Error("Error: " + e.message);
  21808. this._compilationError = e.message;
  21809. if (this.onError) {
  21810. this.onError(this, this._compilationError);
  21811. }
  21812. }
  21813. }
  21814. };
  21815. Object.defineProperty(Effect.prototype, "isSupported", {
  21816. get: function () {
  21817. return this._compilationError === "";
  21818. },
  21819. enumerable: true,
  21820. configurable: true
  21821. });
  21822. Effect.prototype._bindTexture = function (channel, texture) {
  21823. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21824. };
  21825. Effect.prototype.setTexture = function (channel, texture) {
  21826. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  21827. };
  21828. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21829. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21830. };
  21831. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21832. if (!this._valueCache[uniformName]) {
  21833. this._valueCache[uniformName] = new BABYLON.Matrix();
  21834. }
  21835. for (var index = 0; index < 16; index++) {
  21836. this._valueCache[uniformName].m[index] = matrix.m[index];
  21837. }
  21838. };
  21839. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21840. if (!this._valueCache[uniformName]) {
  21841. this._valueCache[uniformName] = [x, y];
  21842. return;
  21843. }
  21844. this._valueCache[uniformName][0] = x;
  21845. this._valueCache[uniformName][1] = y;
  21846. };
  21847. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21848. if (!this._valueCache[uniformName]) {
  21849. this._valueCache[uniformName] = [x, y, z];
  21850. return;
  21851. }
  21852. this._valueCache[uniformName][0] = x;
  21853. this._valueCache[uniformName][1] = y;
  21854. this._valueCache[uniformName][2] = z;
  21855. };
  21856. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21857. if (!this._valueCache[uniformName]) {
  21858. this._valueCache[uniformName] = [x, y, z, w];
  21859. return;
  21860. }
  21861. this._valueCache[uniformName][0] = x;
  21862. this._valueCache[uniformName][1] = y;
  21863. this._valueCache[uniformName][2] = z;
  21864. this._valueCache[uniformName][3] = w;
  21865. };
  21866. Effect.prototype.setArray = function (uniformName, array) {
  21867. this._engine.setArray(this.getUniform(uniformName), array);
  21868. return this;
  21869. };
  21870. Effect.prototype.setArray2 = function (uniformName, array) {
  21871. this._engine.setArray2(this.getUniform(uniformName), array);
  21872. return this;
  21873. };
  21874. Effect.prototype.setArray3 = function (uniformName, array) {
  21875. this._engine.setArray3(this.getUniform(uniformName), array);
  21876. return this;
  21877. };
  21878. Effect.prototype.setArray4 = function (uniformName, array) {
  21879. this._engine.setArray4(this.getUniform(uniformName), array);
  21880. return this;
  21881. };
  21882. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21883. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21884. return this;
  21885. };
  21886. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21887. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  21888. // return this;
  21889. // this._cacheMatrix(uniformName, matrix);
  21890. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21891. return this;
  21892. };
  21893. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21894. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21895. return this;
  21896. };
  21897. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  21898. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  21899. return this;
  21900. };
  21901. Effect.prototype.setFloat = function (uniformName, value) {
  21902. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  21903. return this;
  21904. this._valueCache[uniformName] = value;
  21905. this._engine.setFloat(this.getUniform(uniformName), value);
  21906. return this;
  21907. };
  21908. Effect.prototype.setBool = function (uniformName, bool) {
  21909. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  21910. return this;
  21911. this._valueCache[uniformName] = bool;
  21912. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21913. return this;
  21914. };
  21915. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21916. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  21917. return this;
  21918. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  21919. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21920. return this;
  21921. };
  21922. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21923. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  21924. return this;
  21925. this._cacheFloat2(uniformName, x, y);
  21926. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21927. return this;
  21928. };
  21929. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21930. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  21931. return this;
  21932. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  21933. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21934. return this;
  21935. };
  21936. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21937. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  21938. return this;
  21939. this._cacheFloat3(uniformName, x, y, z);
  21940. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21941. return this;
  21942. };
  21943. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21944. 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)
  21945. return this;
  21946. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  21947. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21948. return this;
  21949. };
  21950. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21951. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  21952. return this;
  21953. this._cacheFloat4(uniformName, x, y, z, w);
  21954. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21955. return this;
  21956. };
  21957. Effect.prototype.setColor3 = function (uniformName, color3) {
  21958. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  21959. return this;
  21960. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  21961. this._engine.setColor3(this.getUniform(uniformName), color3);
  21962. return this;
  21963. };
  21964. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21965. 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)
  21966. return this;
  21967. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  21968. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21969. return this;
  21970. };
  21971. // Statics
  21972. Effect.ShadersStore = {};
  21973. Effect.IncludesShadersStore = {};
  21974. return Effect;
  21975. })();
  21976. BABYLON.Effect = Effect;
  21977. })(BABYLON || (BABYLON = {}));
  21978. var BABYLON;
  21979. (function (BABYLON) {
  21980. var maxSimultaneousLights = 4;
  21981. var MaterialHelper = (function () {
  21982. function MaterialHelper() {
  21983. }
  21984. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  21985. var lightIndex = 0;
  21986. var needNormals = false;
  21987. for (var index = 0; index < scene.lights.length; index++) {
  21988. var light = scene.lights[index];
  21989. if (!light.isEnabled()) {
  21990. continue;
  21991. }
  21992. // Excluded check
  21993. if (light._excludedMeshesIds.length > 0) {
  21994. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  21995. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  21996. if (excludedMesh) {
  21997. light.excludedMeshes.push(excludedMesh);
  21998. }
  21999. }
  22000. light._excludedMeshesIds = [];
  22001. }
  22002. // Included check
  22003. if (light._includedOnlyMeshesIds.length > 0) {
  22004. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22005. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22006. if (includedOnlyMesh) {
  22007. light.includedOnlyMeshes.push(includedOnlyMesh);
  22008. }
  22009. }
  22010. light._includedOnlyMeshesIds = [];
  22011. }
  22012. if (!light.canAffectMesh(mesh)) {
  22013. continue;
  22014. }
  22015. needNormals = true;
  22016. defines["LIGHT" + lightIndex] = true;
  22017. var type;
  22018. if (light instanceof BABYLON.SpotLight) {
  22019. type = "SPOTLIGHT" + lightIndex;
  22020. }
  22021. else if (light instanceof BABYLON.HemisphericLight) {
  22022. type = "HEMILIGHT" + lightIndex;
  22023. }
  22024. else if (light instanceof BABYLON.PointLight) {
  22025. type = "POINTLIGHT" + lightIndex;
  22026. }
  22027. else {
  22028. type = "DIRLIGHT" + lightIndex;
  22029. }
  22030. defines[type] = true;
  22031. // Specular
  22032. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22033. defines["SPECULARTERM"] = true;
  22034. }
  22035. // Shadows
  22036. if (scene.shadowsEnabled) {
  22037. var shadowGenerator = light.getShadowGenerator();
  22038. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22039. defines["SHADOW" + lightIndex] = true;
  22040. defines["SHADOWS"] = true;
  22041. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22042. defines["SHADOWVSM" + lightIndex] = true;
  22043. }
  22044. if (shadowGenerator.usePoissonSampling) {
  22045. defines["SHADOWPCF" + lightIndex] = true;
  22046. }
  22047. }
  22048. }
  22049. lightIndex++;
  22050. if (lightIndex === maxSimultaneousLights)
  22051. break;
  22052. }
  22053. return needNormals;
  22054. };
  22055. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  22056. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22057. if (!defines["LIGHT" + lightIndex]) {
  22058. continue;
  22059. }
  22060. if (lightIndex > 0) {
  22061. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22062. }
  22063. if (defines["SHADOW" + lightIndex]) {
  22064. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22065. }
  22066. if (defines["SHADOWPCF" + lightIndex]) {
  22067. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22068. }
  22069. if (defines["SHADOWVSM" + lightIndex]) {
  22070. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22071. }
  22072. }
  22073. };
  22074. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22075. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22076. fallbacks.addCPUSkinningFallback(0, mesh);
  22077. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22078. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22079. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22082. }
  22083. }
  22084. };
  22085. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22086. if (defines["INSTANCES"]) {
  22087. attribs.push("world0");
  22088. attribs.push("world1");
  22089. attribs.push("world2");
  22090. attribs.push("world3");
  22091. }
  22092. };
  22093. // Bindings
  22094. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22095. var shadowGenerator = light.getShadowGenerator();
  22096. if (mesh.receiveShadows && shadowGenerator) {
  22097. if (!light.needCube()) {
  22098. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22099. }
  22100. else {
  22101. if (!depthValuesAlreadySet) {
  22102. depthValuesAlreadySet = true;
  22103. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22104. }
  22105. }
  22106. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22107. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22108. }
  22109. return depthValuesAlreadySet;
  22110. };
  22111. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22112. if (light instanceof BABYLON.PointLight) {
  22113. // Point Light
  22114. light.transferToEffect(effect, "vLightData" + lightIndex);
  22115. }
  22116. else if (light instanceof BABYLON.DirectionalLight) {
  22117. // Directional Light
  22118. light.transferToEffect(effect, "vLightData" + lightIndex);
  22119. }
  22120. else if (light instanceof BABYLON.SpotLight) {
  22121. // Spot Light
  22122. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22123. }
  22124. else if (light instanceof BABYLON.HemisphericLight) {
  22125. // Hemispheric Light
  22126. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22127. }
  22128. };
  22129. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  22130. var lightIndex = 0;
  22131. var depthValuesAlreadySet = false;
  22132. for (var index = 0; index < scene.lights.length; index++) {
  22133. var light = scene.lights[index];
  22134. if (!light.isEnabled()) {
  22135. continue;
  22136. }
  22137. if (!light.canAffectMesh(mesh)) {
  22138. continue;
  22139. }
  22140. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22141. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22142. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22143. if (defines["SPECULARTERM"]) {
  22144. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22145. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22146. }
  22147. // Shadows
  22148. if (scene.shadowsEnabled) {
  22149. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22150. }
  22151. lightIndex++;
  22152. if (lightIndex === maxSimultaneousLights)
  22153. break;
  22154. }
  22155. };
  22156. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22157. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22158. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22159. effect.setColor3("vFogColor", scene.fogColor);
  22160. }
  22161. };
  22162. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22163. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22164. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22165. }
  22166. };
  22167. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22168. if (defines["LOGARITHMICDEPTH"]) {
  22169. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22170. }
  22171. };
  22172. MaterialHelper.BindClipPlane = function (effect, scene) {
  22173. if (scene.clipPlane) {
  22174. var clipPlane = scene.clipPlane;
  22175. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22176. }
  22177. };
  22178. return MaterialHelper;
  22179. })();
  22180. BABYLON.MaterialHelper = MaterialHelper;
  22181. })(BABYLON || (BABYLON = {}));
  22182. var BABYLON;
  22183. (function (BABYLON) {
  22184. var FresnelParameters = (function () {
  22185. function FresnelParameters() {
  22186. this.isEnabled = true;
  22187. this.leftColor = BABYLON.Color3.White();
  22188. this.rightColor = BABYLON.Color3.Black();
  22189. this.bias = 0;
  22190. this.power = 1;
  22191. }
  22192. FresnelParameters.prototype.clone = function () {
  22193. var newFresnelParameters = new FresnelParameters();
  22194. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22195. return new FresnelParameters;
  22196. };
  22197. FresnelParameters.prototype.serialize = function () {
  22198. var serializationObject = {};
  22199. serializationObject.isEnabled = this.isEnabled;
  22200. serializationObject.leftColor = this.leftColor;
  22201. serializationObject.rightColor = this.rightColor;
  22202. serializationObject.bias = this.bias;
  22203. serializationObject.power = this.power;
  22204. return serializationObject;
  22205. };
  22206. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22207. var fresnelParameters = new FresnelParameters();
  22208. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22209. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22210. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22211. fresnelParameters.bias = parsedFresnelParameters.bias;
  22212. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22213. return fresnelParameters;
  22214. };
  22215. return FresnelParameters;
  22216. })();
  22217. BABYLON.FresnelParameters = FresnelParameters;
  22218. })(BABYLON || (BABYLON = {}));
  22219. var BABYLON;
  22220. (function (BABYLON) {
  22221. var MaterialDefines = (function () {
  22222. function MaterialDefines() {
  22223. }
  22224. MaterialDefines.prototype.isEqual = function (other) {
  22225. for (var index = 0; index < this._keys.length; index++) {
  22226. var prop = this._keys[index];
  22227. if (this[prop] !== other[prop]) {
  22228. return false;
  22229. }
  22230. }
  22231. return true;
  22232. };
  22233. MaterialDefines.prototype.cloneTo = function (other) {
  22234. for (var index = 0; index < this._keys.length; index++) {
  22235. var prop = this._keys[index];
  22236. other[prop] = this[prop];
  22237. }
  22238. };
  22239. MaterialDefines.prototype.reset = function () {
  22240. for (var index = 0; index < this._keys.length; index++) {
  22241. var prop = this._keys[index];
  22242. if (typeof (this[prop]) === "number") {
  22243. this[prop] = 0;
  22244. }
  22245. else {
  22246. this[prop] = false;
  22247. }
  22248. }
  22249. };
  22250. MaterialDefines.prototype.toString = function () {
  22251. var result = "";
  22252. for (var index = 0; index < this._keys.length; index++) {
  22253. var prop = this._keys[index];
  22254. if (typeof (this[prop]) === "number") {
  22255. result += "#define " + prop + " " + this[prop] + "\n";
  22256. }
  22257. else if (this[prop]) {
  22258. result += "#define " + prop + "\n";
  22259. }
  22260. }
  22261. return result;
  22262. };
  22263. return MaterialDefines;
  22264. })();
  22265. BABYLON.MaterialDefines = MaterialDefines;
  22266. var Material = (function () {
  22267. function Material(name, scene, doNotAdd) {
  22268. this.name = name;
  22269. this.checkReadyOnEveryCall = false;
  22270. this.checkReadyOnlyOnce = false;
  22271. this.state = "";
  22272. this.alpha = 1.0;
  22273. this.backFaceCulling = true;
  22274. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22275. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22276. this.disableDepthWrite = false;
  22277. this.fogEnabled = true;
  22278. this.pointSize = 1.0;
  22279. this.zOffset = 0;
  22280. this._wasPreviouslyReady = false;
  22281. this._fillMode = Material.TriangleFillMode;
  22282. this.id = name;
  22283. this._scene = scene;
  22284. if (!doNotAdd) {
  22285. scene.materials.push(this);
  22286. }
  22287. }
  22288. Object.defineProperty(Material, "TriangleFillMode", {
  22289. get: function () {
  22290. return Material._TriangleFillMode;
  22291. },
  22292. enumerable: true,
  22293. configurable: true
  22294. });
  22295. Object.defineProperty(Material, "WireFrameFillMode", {
  22296. get: function () {
  22297. return Material._WireFrameFillMode;
  22298. },
  22299. enumerable: true,
  22300. configurable: true
  22301. });
  22302. Object.defineProperty(Material, "PointFillMode", {
  22303. get: function () {
  22304. return Material._PointFillMode;
  22305. },
  22306. enumerable: true,
  22307. configurable: true
  22308. });
  22309. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22310. get: function () {
  22311. return Material._ClockWiseSideOrientation;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22317. get: function () {
  22318. return Material._CounterClockWiseSideOrientation;
  22319. },
  22320. enumerable: true,
  22321. configurable: true
  22322. });
  22323. Object.defineProperty(Material.prototype, "wireframe", {
  22324. get: function () {
  22325. return this._fillMode === Material.WireFrameFillMode;
  22326. },
  22327. set: function (value) {
  22328. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Object.defineProperty(Material.prototype, "pointsCloud", {
  22334. get: function () {
  22335. return this._fillMode === Material.PointFillMode;
  22336. },
  22337. set: function (value) {
  22338. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22339. },
  22340. enumerable: true,
  22341. configurable: true
  22342. });
  22343. Object.defineProperty(Material.prototype, "fillMode", {
  22344. get: function () {
  22345. return this._fillMode;
  22346. },
  22347. set: function (value) {
  22348. this._fillMode = value;
  22349. },
  22350. enumerable: true,
  22351. configurable: true
  22352. });
  22353. /**
  22354. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22355. * subclasses should override adding information pertainent to themselves
  22356. */
  22357. Material.prototype.toString = function (fullDetails) {
  22358. var ret = "Name: " + this.name;
  22359. if (fullDetails) {
  22360. }
  22361. return ret;
  22362. };
  22363. Object.defineProperty(Material.prototype, "isFrozen", {
  22364. get: function () {
  22365. return this.checkReadyOnlyOnce;
  22366. },
  22367. enumerable: true,
  22368. configurable: true
  22369. });
  22370. Material.prototype.freeze = function () {
  22371. this.checkReadyOnlyOnce = true;
  22372. };
  22373. Material.prototype.unfreeze = function () {
  22374. this.checkReadyOnlyOnce = false;
  22375. };
  22376. Material.prototype.isReady = function (mesh, useInstances) {
  22377. return true;
  22378. };
  22379. Material.prototype.getEffect = function () {
  22380. return this._effect;
  22381. };
  22382. Material.prototype.getScene = function () {
  22383. return this._scene;
  22384. };
  22385. Material.prototype.needAlphaBlending = function () {
  22386. return (this.alpha < 1.0);
  22387. };
  22388. Material.prototype.needAlphaTesting = function () {
  22389. return false;
  22390. };
  22391. Material.prototype.getAlphaTestTexture = function () {
  22392. return null;
  22393. };
  22394. Material.prototype.trackCreation = function (onCompiled, onError) {
  22395. };
  22396. Material.prototype.markDirty = function () {
  22397. this._wasPreviouslyReady = false;
  22398. };
  22399. Material.prototype._preBind = function () {
  22400. var engine = this._scene.getEngine();
  22401. engine.enableEffect(this._effect);
  22402. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22403. };
  22404. Material.prototype.bind = function (world, mesh) {
  22405. this._scene._cachedMaterial = this;
  22406. if (this.onBind) {
  22407. this.onBind(this, mesh);
  22408. }
  22409. if (this.disableDepthWrite) {
  22410. var engine = this._scene.getEngine();
  22411. this._cachedDepthWriteState = engine.getDepthWrite();
  22412. engine.setDepthWrite(false);
  22413. }
  22414. };
  22415. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22416. };
  22417. Material.prototype.unbind = function () {
  22418. if (this.disableDepthWrite) {
  22419. var engine = this._scene.getEngine();
  22420. engine.setDepthWrite(this._cachedDepthWriteState);
  22421. }
  22422. };
  22423. Material.prototype.clone = function (name) {
  22424. return null;
  22425. };
  22426. Material.prototype.getBindedMeshes = function () {
  22427. var result = new Array();
  22428. for (var index = 0; index < this._scene.meshes.length; index++) {
  22429. var mesh = this._scene.meshes[index];
  22430. if (mesh.material === this) {
  22431. result.push(mesh);
  22432. }
  22433. }
  22434. return result;
  22435. };
  22436. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22437. // Animations
  22438. this.getScene().stopAnimation(this);
  22439. // Remove from scene
  22440. var index = this._scene.materials.indexOf(this);
  22441. if (index >= 0) {
  22442. this._scene.materials.splice(index, 1);
  22443. }
  22444. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22445. if (forceDisposeEffect && this._effect) {
  22446. this._scene.getEngine()._releaseEffect(this._effect);
  22447. this._effect = null;
  22448. }
  22449. // Remove from meshes
  22450. for (index = 0; index < this._scene.meshes.length; index++) {
  22451. var mesh = this._scene.meshes[index];
  22452. if (mesh.material === this) {
  22453. mesh.material = null;
  22454. }
  22455. }
  22456. // Callback
  22457. if (this.onDispose) {
  22458. this.onDispose();
  22459. }
  22460. };
  22461. Material.prototype.serialize = function () {
  22462. return BABYLON.SerializationHelper.Serialize(this);
  22463. };
  22464. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22465. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22466. multiMaterial.id = parsedMultiMaterial.id;
  22467. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22468. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22469. var subMatId = parsedMultiMaterial.materials[matIndex];
  22470. if (subMatId) {
  22471. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22472. }
  22473. else {
  22474. multiMaterial.subMaterials.push(null);
  22475. }
  22476. }
  22477. return multiMaterial;
  22478. };
  22479. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22480. if (!parsedMaterial.customType) {
  22481. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22482. }
  22483. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22484. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22485. ;
  22486. };
  22487. Material._TriangleFillMode = 0;
  22488. Material._WireFrameFillMode = 1;
  22489. Material._PointFillMode = 2;
  22490. Material._ClockWiseSideOrientation = 0;
  22491. Material._CounterClockWiseSideOrientation = 1;
  22492. __decorate([
  22493. BABYLON.serialize()
  22494. ], Material.prototype, "id", void 0);
  22495. __decorate([
  22496. BABYLON.serialize()
  22497. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22498. __decorate([
  22499. BABYLON.serialize()
  22500. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22501. __decorate([
  22502. BABYLON.serialize()
  22503. ], Material.prototype, "state", void 0);
  22504. __decorate([
  22505. BABYLON.serialize()
  22506. ], Material.prototype, "alpha", void 0);
  22507. __decorate([
  22508. BABYLON.serialize()
  22509. ], Material.prototype, "backFaceCulling", void 0);
  22510. __decorate([
  22511. BABYLON.serialize()
  22512. ], Material.prototype, "sideOrientation", void 0);
  22513. __decorate([
  22514. BABYLON.serialize()
  22515. ], Material.prototype, "alphaMode", void 0);
  22516. __decorate([
  22517. BABYLON.serialize()
  22518. ], Material.prototype, "disableDepthWrite", void 0);
  22519. __decorate([
  22520. BABYLON.serialize()
  22521. ], Material.prototype, "fogEnabled", void 0);
  22522. __decorate([
  22523. BABYLON.serialize()
  22524. ], Material.prototype, "pointSize", void 0);
  22525. __decorate([
  22526. BABYLON.serialize()
  22527. ], Material.prototype, "zOffset", void 0);
  22528. __decorate([
  22529. BABYLON.serialize()
  22530. ], Material.prototype, "wireframe", null);
  22531. __decorate([
  22532. BABYLON.serialize()
  22533. ], Material.prototype, "pointsCloud", null);
  22534. __decorate([
  22535. BABYLON.serialize()
  22536. ], Material.prototype, "fillMode", null);
  22537. return Material;
  22538. })();
  22539. BABYLON.Material = Material;
  22540. })(BABYLON || (BABYLON = {}));
  22541. var BABYLON;
  22542. (function (BABYLON) {
  22543. var StandardMaterialDefines = (function (_super) {
  22544. __extends(StandardMaterialDefines, _super);
  22545. function StandardMaterialDefines() {
  22546. _super.call(this);
  22547. this.DIFFUSE = false;
  22548. this.AMBIENT = false;
  22549. this.OPACITY = false;
  22550. this.OPACITYRGB = false;
  22551. this.REFLECTION = false;
  22552. this.EMISSIVE = false;
  22553. this.SPECULAR = false;
  22554. this.BUMP = false;
  22555. this.PARALLAX = false;
  22556. this.PARALLAXOCCLUSION = false;
  22557. this.SPECULAROVERALPHA = false;
  22558. this.CLIPPLANE = false;
  22559. this.ALPHATEST = false;
  22560. this.ALPHAFROMDIFFUSE = false;
  22561. this.POINTSIZE = false;
  22562. this.FOG = false;
  22563. this.LIGHT0 = false;
  22564. this.LIGHT1 = false;
  22565. this.LIGHT2 = false;
  22566. this.LIGHT3 = false;
  22567. this.SPOTLIGHT0 = false;
  22568. this.SPOTLIGHT1 = false;
  22569. this.SPOTLIGHT2 = false;
  22570. this.SPOTLIGHT3 = false;
  22571. this.HEMILIGHT0 = false;
  22572. this.HEMILIGHT1 = false;
  22573. this.HEMILIGHT2 = false;
  22574. this.HEMILIGHT3 = false;
  22575. this.POINTLIGHT0 = false;
  22576. this.POINTLIGHT1 = false;
  22577. this.POINTLIGHT2 = false;
  22578. this.POINTLIGHT3 = false;
  22579. this.DIRLIGHT0 = false;
  22580. this.DIRLIGHT1 = false;
  22581. this.DIRLIGHT2 = false;
  22582. this.DIRLIGHT3 = false;
  22583. this.SPECULARTERM = false;
  22584. this.SHADOW0 = false;
  22585. this.SHADOW1 = false;
  22586. this.SHADOW2 = false;
  22587. this.SHADOW3 = false;
  22588. this.SHADOWS = false;
  22589. this.SHADOWVSM0 = false;
  22590. this.SHADOWVSM1 = false;
  22591. this.SHADOWVSM2 = false;
  22592. this.SHADOWVSM3 = false;
  22593. this.SHADOWPCF0 = false;
  22594. this.SHADOWPCF1 = false;
  22595. this.SHADOWPCF2 = false;
  22596. this.SHADOWPCF3 = false;
  22597. this.DIFFUSEFRESNEL = false;
  22598. this.OPACITYFRESNEL = false;
  22599. this.REFLECTIONFRESNEL = false;
  22600. this.REFRACTIONFRESNEL = false;
  22601. this.EMISSIVEFRESNEL = false;
  22602. this.FRESNEL = false;
  22603. this.NORMAL = false;
  22604. this.UV1 = false;
  22605. this.UV2 = false;
  22606. this.VERTEXCOLOR = false;
  22607. this.VERTEXALPHA = false;
  22608. this.NUM_BONE_INFLUENCERS = 0;
  22609. this.BonesPerMesh = 0;
  22610. this.INSTANCES = false;
  22611. this.GLOSSINESS = false;
  22612. this.ROUGHNESS = false;
  22613. this.EMISSIVEASILLUMINATION = false;
  22614. this.LINKEMISSIVEWITHDIFFUSE = false;
  22615. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22616. this.LIGHTMAP = false;
  22617. this.USELIGHTMAPASSHADOWMAP = false;
  22618. this.REFLECTIONMAP_3D = false;
  22619. this.REFLECTIONMAP_SPHERICAL = false;
  22620. this.REFLECTIONMAP_PLANAR = false;
  22621. this.REFLECTIONMAP_CUBIC = false;
  22622. this.REFLECTIONMAP_PROJECTION = false;
  22623. this.REFLECTIONMAP_SKYBOX = false;
  22624. this.REFLECTIONMAP_EXPLICIT = false;
  22625. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22626. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22627. this.INVERTCUBICMAP = false;
  22628. this.LOGARITHMICDEPTH = false;
  22629. this.REFRACTION = false;
  22630. this.REFRACTIONMAP_3D = false;
  22631. this.REFLECTIONOVERALPHA = false;
  22632. this._keys = Object.keys(this);
  22633. }
  22634. return StandardMaterialDefines;
  22635. })(BABYLON.MaterialDefines);
  22636. var StandardMaterial = (function (_super) {
  22637. __extends(StandardMaterial, _super);
  22638. function StandardMaterial(name, scene) {
  22639. var _this = this;
  22640. _super.call(this, name, scene);
  22641. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22642. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22643. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22644. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22645. this.specularPower = 64;
  22646. this.useAlphaFromDiffuseTexture = false;
  22647. this.useEmissiveAsIllumination = false;
  22648. this.linkEmissiveWithDiffuse = false;
  22649. this.useReflectionFresnelFromSpecular = false;
  22650. this.useSpecularOverAlpha = false;
  22651. this.useReflectionOverAlpha = false;
  22652. this.disableLighting = false;
  22653. this.useParallax = false;
  22654. this.useParallaxOcclusion = false;
  22655. this.parallaxScaleBias = 0.05;
  22656. this.roughness = 0;
  22657. this.indexOfRefraction = 0.98;
  22658. this.invertRefractionY = true;
  22659. this.useLightmapAsShadowmap = false;
  22660. this.useGlossinessFromSpecularMapAlpha = false;
  22661. this._renderTargets = new BABYLON.SmartArray(16);
  22662. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22663. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22664. this._defines = new StandardMaterialDefines();
  22665. this._cachedDefines = new StandardMaterialDefines();
  22666. this._cachedDefines.BonesPerMesh = -1;
  22667. this.getRenderTargetTextures = function () {
  22668. _this._renderTargets.reset();
  22669. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22670. _this._renderTargets.push(_this.reflectionTexture);
  22671. }
  22672. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22673. _this._renderTargets.push(_this.refractionTexture);
  22674. }
  22675. return _this._renderTargets;
  22676. };
  22677. }
  22678. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22679. get: function () {
  22680. return this._useLogarithmicDepth;
  22681. },
  22682. set: function (value) {
  22683. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22684. },
  22685. enumerable: true,
  22686. configurable: true
  22687. });
  22688. StandardMaterial.prototype.needAlphaBlending = function () {
  22689. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22690. };
  22691. StandardMaterial.prototype.needAlphaTesting = function () {
  22692. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22693. };
  22694. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22695. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22696. };
  22697. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22698. return this.diffuseTexture;
  22699. };
  22700. // Methods
  22701. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22702. if (!mesh) {
  22703. return true;
  22704. }
  22705. if (this._defines.INSTANCES !== useInstances) {
  22706. return false;
  22707. }
  22708. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22709. return true;
  22710. }
  22711. return false;
  22712. };
  22713. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22714. if (this.isFrozen) {
  22715. if (this._wasPreviouslyReady) {
  22716. return true;
  22717. }
  22718. }
  22719. var scene = this.getScene();
  22720. if (!this.checkReadyOnEveryCall) {
  22721. if (this._renderId === scene.getRenderId()) {
  22722. if (this._checkCache(scene, mesh, useInstances)) {
  22723. return true;
  22724. }
  22725. }
  22726. }
  22727. var engine = scene.getEngine();
  22728. var needNormals = false;
  22729. var needUVs = false;
  22730. this._defines.reset();
  22731. // Textures
  22732. if (scene.texturesEnabled) {
  22733. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22734. if (!this.diffuseTexture.isReady()) {
  22735. return false;
  22736. }
  22737. else {
  22738. needUVs = true;
  22739. this._defines.DIFFUSE = true;
  22740. }
  22741. }
  22742. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22743. if (!this.ambientTexture.isReady()) {
  22744. return false;
  22745. }
  22746. else {
  22747. needUVs = true;
  22748. this._defines.AMBIENT = true;
  22749. }
  22750. }
  22751. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22752. if (!this.opacityTexture.isReady()) {
  22753. return false;
  22754. }
  22755. else {
  22756. needUVs = true;
  22757. this._defines.OPACITY = true;
  22758. if (this.opacityTexture.getAlphaFromRGB) {
  22759. this._defines.OPACITYRGB = true;
  22760. }
  22761. }
  22762. }
  22763. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22764. if (!this.reflectionTexture.isReady()) {
  22765. return false;
  22766. }
  22767. else {
  22768. needNormals = true;
  22769. this._defines.REFLECTION = true;
  22770. if (this.roughness > 0) {
  22771. this._defines.ROUGHNESS = true;
  22772. }
  22773. if (this.useReflectionOverAlpha) {
  22774. this._defines.REFLECTIONOVERALPHA = true;
  22775. }
  22776. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22777. this._defines.INVERTCUBICMAP = true;
  22778. }
  22779. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22780. switch (this.reflectionTexture.coordinatesMode) {
  22781. case BABYLON.Texture.CUBIC_MODE:
  22782. case BABYLON.Texture.INVCUBIC_MODE:
  22783. this._defines.REFLECTIONMAP_CUBIC = true;
  22784. break;
  22785. case BABYLON.Texture.EXPLICIT_MODE:
  22786. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22787. break;
  22788. case BABYLON.Texture.PLANAR_MODE:
  22789. this._defines.REFLECTIONMAP_PLANAR = true;
  22790. break;
  22791. case BABYLON.Texture.PROJECTION_MODE:
  22792. this._defines.REFLECTIONMAP_PROJECTION = true;
  22793. break;
  22794. case BABYLON.Texture.SKYBOX_MODE:
  22795. this._defines.REFLECTIONMAP_SKYBOX = true;
  22796. break;
  22797. case BABYLON.Texture.SPHERICAL_MODE:
  22798. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22799. break;
  22800. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22801. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22802. break;
  22803. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22804. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22805. break;
  22806. }
  22807. }
  22808. }
  22809. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22810. if (!this.emissiveTexture.isReady()) {
  22811. return false;
  22812. }
  22813. else {
  22814. needUVs = true;
  22815. this._defines.EMISSIVE = true;
  22816. }
  22817. }
  22818. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22819. if (!this.lightmapTexture.isReady()) {
  22820. return false;
  22821. }
  22822. else {
  22823. needUVs = true;
  22824. this._defines.LIGHTMAP = true;
  22825. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  22826. }
  22827. }
  22828. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22829. if (!this.specularTexture.isReady()) {
  22830. return false;
  22831. }
  22832. else {
  22833. needUVs = true;
  22834. this._defines.SPECULAR = true;
  22835. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  22836. }
  22837. }
  22838. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  22839. if (!this.bumpTexture.isReady()) {
  22840. return false;
  22841. }
  22842. else {
  22843. needUVs = true;
  22844. this._defines.BUMP = true;
  22845. if (this.useParallax) {
  22846. this._defines.PARALLAX = true;
  22847. if (this.useParallaxOcclusion) {
  22848. this._defines.PARALLAXOCCLUSION = true;
  22849. }
  22850. }
  22851. }
  22852. }
  22853. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22854. if (!this.refractionTexture.isReady()) {
  22855. return false;
  22856. }
  22857. else {
  22858. needUVs = true;
  22859. this._defines.REFRACTION = true;
  22860. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  22861. }
  22862. }
  22863. }
  22864. // Effect
  22865. if (scene.clipPlane) {
  22866. this._defines.CLIPPLANE = true;
  22867. }
  22868. if (engine.getAlphaTesting()) {
  22869. this._defines.ALPHATEST = true;
  22870. }
  22871. if (this._shouldUseAlphaFromDiffuseTexture()) {
  22872. this._defines.ALPHAFROMDIFFUSE = true;
  22873. }
  22874. if (this.useEmissiveAsIllumination) {
  22875. this._defines.EMISSIVEASILLUMINATION = true;
  22876. }
  22877. if (this.linkEmissiveWithDiffuse) {
  22878. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  22879. }
  22880. if (this.useLogarithmicDepth) {
  22881. this._defines.LOGARITHMICDEPTH = true;
  22882. }
  22883. // Point size
  22884. if (this.pointsCloud || scene.forcePointsCloud) {
  22885. this._defines.POINTSIZE = true;
  22886. }
  22887. // Fog
  22888. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22889. this._defines.FOG = true;
  22890. }
  22891. if (scene.lightsEnabled && !this.disableLighting) {
  22892. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  22893. }
  22894. if (StandardMaterial.FresnelEnabled) {
  22895. // Fresnel
  22896. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  22897. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  22898. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  22899. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  22900. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22901. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22902. this._defines.DIFFUSEFRESNEL = true;
  22903. }
  22904. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22905. this._defines.OPACITYFRESNEL = true;
  22906. }
  22907. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22908. this._defines.REFLECTIONFRESNEL = true;
  22909. if (this.useReflectionFresnelFromSpecular) {
  22910. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  22911. }
  22912. }
  22913. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22914. this._defines.REFRACTIONFRESNEL = true;
  22915. }
  22916. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22917. this._defines.EMISSIVEFRESNEL = true;
  22918. }
  22919. needNormals = true;
  22920. this._defines.FRESNEL = true;
  22921. }
  22922. }
  22923. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  22924. this._defines.SPECULAROVERALPHA = true;
  22925. }
  22926. // Attribs
  22927. if (mesh) {
  22928. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22929. this._defines.NORMAL = true;
  22930. }
  22931. if (needUVs) {
  22932. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22933. this._defines.UV1 = true;
  22934. }
  22935. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22936. this._defines.UV2 = true;
  22937. }
  22938. }
  22939. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22940. this._defines.VERTEXCOLOR = true;
  22941. if (mesh.hasVertexAlpha) {
  22942. this._defines.VERTEXALPHA = true;
  22943. }
  22944. }
  22945. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22946. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  22947. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  22948. }
  22949. // Instances
  22950. if (useInstances) {
  22951. this._defines.INSTANCES = true;
  22952. }
  22953. }
  22954. // Get correct effect
  22955. if (!this._defines.isEqual(this._cachedDefines)) {
  22956. this._defines.cloneTo(this._cachedDefines);
  22957. scene.resetCachedMaterial();
  22958. // Fallbacks
  22959. var fallbacks = new BABYLON.EffectFallbacks();
  22960. if (this._defines.REFLECTION) {
  22961. fallbacks.addFallback(0, "REFLECTION");
  22962. }
  22963. if (this._defines.SPECULAR) {
  22964. fallbacks.addFallback(0, "SPECULAR");
  22965. }
  22966. if (this._defines.BUMP) {
  22967. fallbacks.addFallback(0, "BUMP");
  22968. }
  22969. if (this._defines.PARALLAX) {
  22970. fallbacks.addFallback(1, "PARALLAX");
  22971. }
  22972. if (this._defines.PARALLAXOCCLUSION) {
  22973. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  22974. }
  22975. if (this._defines.SPECULAROVERALPHA) {
  22976. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  22977. }
  22978. if (this._defines.FOG) {
  22979. fallbacks.addFallback(1, "FOG");
  22980. }
  22981. if (this._defines.POINTSIZE) {
  22982. fallbacks.addFallback(0, "POINTSIZE");
  22983. }
  22984. if (this._defines.LOGARITHMICDEPTH) {
  22985. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  22986. }
  22987. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  22988. if (this._defines.SPECULARTERM) {
  22989. fallbacks.addFallback(0, "SPECULARTERM");
  22990. }
  22991. if (this._defines.DIFFUSEFRESNEL) {
  22992. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  22993. }
  22994. if (this._defines.OPACITYFRESNEL) {
  22995. fallbacks.addFallback(2, "OPACITYFRESNEL");
  22996. }
  22997. if (this._defines.REFLECTIONFRESNEL) {
  22998. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  22999. }
  23000. if (this._defines.EMISSIVEFRESNEL) {
  23001. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23002. }
  23003. if (this._defines.FRESNEL) {
  23004. fallbacks.addFallback(4, "FRESNEL");
  23005. }
  23006. //Attributes
  23007. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23008. if (this._defines.NORMAL) {
  23009. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23010. }
  23011. if (this._defines.UV1) {
  23012. attribs.push(BABYLON.VertexBuffer.UVKind);
  23013. }
  23014. if (this._defines.UV2) {
  23015. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23016. }
  23017. if (this._defines.VERTEXCOLOR) {
  23018. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23019. }
  23020. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23021. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23022. // Legacy browser patch
  23023. var shaderName = "default";
  23024. if (!scene.getEngine().getCaps().standardDerivatives) {
  23025. shaderName = "legacydefault";
  23026. }
  23027. var join = this._defines.toString();
  23028. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23029. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  23030. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  23031. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  23032. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  23033. "vFogInfos", "vFogColor", "pointSize",
  23034. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23035. "mBones",
  23036. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23037. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  23038. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23039. "logarithmicDepthConstant"
  23040. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  23041. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  23042. ], join, fallbacks, this.onCompiled, this.onError);
  23043. }
  23044. if (!this._effect.isReady()) {
  23045. return false;
  23046. }
  23047. this._renderId = scene.getRenderId();
  23048. this._wasPreviouslyReady = true;
  23049. if (mesh) {
  23050. if (!mesh._materialDefines) {
  23051. mesh._materialDefines = new StandardMaterialDefines();
  23052. }
  23053. this._defines.cloneTo(mesh._materialDefines);
  23054. }
  23055. return true;
  23056. };
  23057. StandardMaterial.prototype.unbind = function () {
  23058. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23059. this._effect.setTexture("reflection2DSampler", null);
  23060. }
  23061. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23062. this._effect.setTexture("refraction2DSampler", null);
  23063. }
  23064. _super.prototype.unbind.call(this);
  23065. };
  23066. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23067. this._effect.setMatrix("world", world);
  23068. };
  23069. StandardMaterial.prototype.bind = function (world, mesh) {
  23070. var scene = this.getScene();
  23071. // Matrices
  23072. this.bindOnlyWorldMatrix(world);
  23073. // Bones
  23074. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23075. if (scene.getCachedMaterial() !== this) {
  23076. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23077. if (StandardMaterial.FresnelEnabled) {
  23078. // Fresnel
  23079. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23080. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23081. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23082. }
  23083. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23084. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23085. }
  23086. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23087. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23088. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23089. }
  23090. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23091. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23092. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23093. }
  23094. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23095. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23096. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23097. }
  23098. }
  23099. // Textures
  23100. if (scene.texturesEnabled) {
  23101. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23102. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23103. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23104. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23105. }
  23106. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23107. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23108. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23109. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23110. }
  23111. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23112. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23113. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23114. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23115. }
  23116. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23117. if (this.reflectionTexture.isCube) {
  23118. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23119. }
  23120. else {
  23121. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23122. }
  23123. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23124. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23125. }
  23126. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23127. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23128. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23129. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23130. }
  23131. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23132. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23133. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23134. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23135. }
  23136. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23137. this._effect.setTexture("specularSampler", this.specularTexture);
  23138. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23139. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23140. }
  23141. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23142. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23143. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23144. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23145. }
  23146. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23147. var depth = 1.0;
  23148. if (this.refractionTexture.isCube) {
  23149. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23150. }
  23151. else {
  23152. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23153. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23154. if (this.refractionTexture.depth) {
  23155. depth = this.refractionTexture.depth;
  23156. }
  23157. }
  23158. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23159. }
  23160. }
  23161. // Clip plane
  23162. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23163. // Point size
  23164. if (this.pointsCloud) {
  23165. this._effect.setFloat("pointSize", this.pointSize);
  23166. }
  23167. // Colors
  23168. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23169. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23170. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23171. if (this._defines.SPECULARTERM) {
  23172. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23173. }
  23174. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23175. }
  23176. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23177. // Diffuse
  23178. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23179. // Lights
  23180. if (scene.lightsEnabled && !this.disableLighting) {
  23181. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  23182. }
  23183. // View
  23184. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23185. this._effect.setMatrix("view", scene.getViewMatrix());
  23186. }
  23187. // Fog
  23188. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23189. // Log. depth
  23190. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23191. }
  23192. _super.prototype.bind.call(this, world, mesh);
  23193. };
  23194. StandardMaterial.prototype.getAnimatables = function () {
  23195. var results = [];
  23196. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23197. results.push(this.diffuseTexture);
  23198. }
  23199. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23200. results.push(this.ambientTexture);
  23201. }
  23202. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23203. results.push(this.opacityTexture);
  23204. }
  23205. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23206. results.push(this.reflectionTexture);
  23207. }
  23208. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23209. results.push(this.emissiveTexture);
  23210. }
  23211. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23212. results.push(this.specularTexture);
  23213. }
  23214. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23215. results.push(this.bumpTexture);
  23216. }
  23217. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23218. results.push(this.lightmapTexture);
  23219. }
  23220. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23221. results.push(this.refractionTexture);
  23222. }
  23223. return results;
  23224. };
  23225. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23226. if (forceDisposeTextures) {
  23227. if (this.diffuseTexture) {
  23228. this.diffuseTexture.dispose();
  23229. }
  23230. if (this.ambientTexture) {
  23231. this.ambientTexture.dispose();
  23232. }
  23233. if (this.opacityTexture) {
  23234. this.opacityTexture.dispose();
  23235. }
  23236. if (this.reflectionTexture) {
  23237. this.reflectionTexture.dispose();
  23238. }
  23239. if (this.emissiveTexture) {
  23240. this.emissiveTexture.dispose();
  23241. }
  23242. if (this.specularTexture) {
  23243. this.specularTexture.dispose();
  23244. }
  23245. if (this.bumpTexture) {
  23246. this.bumpTexture.dispose();
  23247. }
  23248. if (this.lightmapTexture) {
  23249. this.lightmapTexture.dispose();
  23250. }
  23251. if (this.refractionTexture) {
  23252. this.refractionTexture.dispose();
  23253. }
  23254. }
  23255. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  23256. };
  23257. StandardMaterial.prototype.clone = function (name) {
  23258. var _this = this;
  23259. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23260. };
  23261. StandardMaterial.prototype.serialize = function () {
  23262. return BABYLON.SerializationHelper.Serialize(this);
  23263. };
  23264. // Statics
  23265. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23266. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23267. };
  23268. // Flags used to enable or disable a type of texture for all Standard Materials
  23269. StandardMaterial.DiffuseTextureEnabled = true;
  23270. StandardMaterial.AmbientTextureEnabled = true;
  23271. StandardMaterial.OpacityTextureEnabled = true;
  23272. StandardMaterial.ReflectionTextureEnabled = true;
  23273. StandardMaterial.EmissiveTextureEnabled = true;
  23274. StandardMaterial.SpecularTextureEnabled = true;
  23275. StandardMaterial.BumpTextureEnabled = true;
  23276. StandardMaterial.FresnelEnabled = true;
  23277. StandardMaterial.LightmapTextureEnabled = true;
  23278. StandardMaterial.RefractionTextureEnabled = true;
  23279. __decorate([
  23280. BABYLON.serializeAsTexture()
  23281. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23282. __decorate([
  23283. BABYLON.serializeAsTexture()
  23284. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23285. __decorate([
  23286. BABYLON.serializeAsTexture()
  23287. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23288. __decorate([
  23289. BABYLON.serializeAsTexture()
  23290. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23291. __decorate([
  23292. BABYLON.serializeAsTexture()
  23293. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23294. __decorate([
  23295. BABYLON.serializeAsTexture()
  23296. ], StandardMaterial.prototype, "specularTexture", void 0);
  23297. __decorate([
  23298. BABYLON.serializeAsTexture()
  23299. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23300. __decorate([
  23301. BABYLON.serializeAsTexture()
  23302. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23303. __decorate([
  23304. BABYLON.serializeAsTexture()
  23305. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23306. __decorate([
  23307. BABYLON.serializeAsColor3("ambient")
  23308. ], StandardMaterial.prototype, "ambientColor", void 0);
  23309. __decorate([
  23310. BABYLON.serializeAsColor3("diffuse")
  23311. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23312. __decorate([
  23313. BABYLON.serializeAsColor3("specular")
  23314. ], StandardMaterial.prototype, "specularColor", void 0);
  23315. __decorate([
  23316. BABYLON.serializeAsColor3("emissive")
  23317. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23318. __decorate([
  23319. BABYLON.serialize()
  23320. ], StandardMaterial.prototype, "specularPower", void 0);
  23321. __decorate([
  23322. BABYLON.serialize()
  23323. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23324. __decorate([
  23325. BABYLON.serialize()
  23326. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23327. __decorate([
  23328. BABYLON.serialize()
  23329. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23330. __decorate([
  23331. BABYLON.serialize()
  23332. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23333. __decorate([
  23334. BABYLON.serialize()
  23335. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23336. __decorate([
  23337. BABYLON.serialize()
  23338. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23339. __decorate([
  23340. BABYLON.serialize()
  23341. ], StandardMaterial.prototype, "disableLighting", void 0);
  23342. __decorate([
  23343. BABYLON.serialize()
  23344. ], StandardMaterial.prototype, "useParallax", void 0);
  23345. __decorate([
  23346. BABYLON.serialize()
  23347. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23348. __decorate([
  23349. BABYLON.serialize()
  23350. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23351. __decorate([
  23352. BABYLON.serialize()
  23353. ], StandardMaterial.prototype, "roughness", void 0);
  23354. __decorate([
  23355. BABYLON.serialize()
  23356. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23357. __decorate([
  23358. BABYLON.serialize()
  23359. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23360. __decorate([
  23361. BABYLON.serialize()
  23362. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23363. __decorate([
  23364. BABYLON.serializeAsFresnelParameters()
  23365. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23366. __decorate([
  23367. BABYLON.serializeAsFresnelParameters()
  23368. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23369. __decorate([
  23370. BABYLON.serializeAsFresnelParameters()
  23371. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23372. __decorate([
  23373. BABYLON.serializeAsFresnelParameters()
  23374. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23375. __decorate([
  23376. BABYLON.serializeAsFresnelParameters()
  23377. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23378. __decorate([
  23379. BABYLON.serialize()
  23380. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23381. __decorate([
  23382. BABYLON.serialize()
  23383. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23384. return StandardMaterial;
  23385. })(BABYLON.Material);
  23386. BABYLON.StandardMaterial = StandardMaterial;
  23387. })(BABYLON || (BABYLON = {}));
  23388. var BABYLON;
  23389. (function (BABYLON) {
  23390. var MultiMaterial = (function (_super) {
  23391. __extends(MultiMaterial, _super);
  23392. function MultiMaterial(name, scene) {
  23393. _super.call(this, name, scene, true);
  23394. this.subMaterials = new Array();
  23395. scene.multiMaterials.push(this);
  23396. }
  23397. // Properties
  23398. MultiMaterial.prototype.getSubMaterial = function (index) {
  23399. if (index < 0 || index >= this.subMaterials.length) {
  23400. return this.getScene().defaultMaterial;
  23401. }
  23402. return this.subMaterials[index];
  23403. };
  23404. // Methods
  23405. MultiMaterial.prototype.isReady = function (mesh) {
  23406. for (var index = 0; index < this.subMaterials.length; index++) {
  23407. var subMaterial = this.subMaterials[index];
  23408. if (subMaterial) {
  23409. if (!this.subMaterials[index].isReady(mesh)) {
  23410. return false;
  23411. }
  23412. }
  23413. }
  23414. return true;
  23415. };
  23416. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23417. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23418. for (var index = 0; index < this.subMaterials.length; index++) {
  23419. var subMaterial = null;
  23420. if (cloneChildren) {
  23421. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23422. }
  23423. else {
  23424. subMaterial = this.subMaterials[index];
  23425. }
  23426. newMultiMaterial.subMaterials.push(subMaterial);
  23427. }
  23428. return newMultiMaterial;
  23429. };
  23430. MultiMaterial.prototype.serialize = function () {
  23431. var serializationObject = {};
  23432. serializationObject.name = this.name;
  23433. serializationObject.id = this.id;
  23434. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23435. serializationObject.materials = [];
  23436. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23437. var subMat = this.subMaterials[matIndex];
  23438. if (subMat) {
  23439. serializationObject.materials.push(subMat.id);
  23440. }
  23441. else {
  23442. serializationObject.materials.push(null);
  23443. }
  23444. }
  23445. return serializationObject;
  23446. };
  23447. return MultiMaterial;
  23448. })(BABYLON.Material);
  23449. BABYLON.MultiMaterial = MultiMaterial;
  23450. })(BABYLON || (BABYLON = {}));
  23451. var BABYLON;
  23452. (function (BABYLON) {
  23453. var SceneLoader = (function () {
  23454. function SceneLoader() {
  23455. }
  23456. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23457. get: function () {
  23458. return 0;
  23459. },
  23460. enumerable: true,
  23461. configurable: true
  23462. });
  23463. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23464. get: function () {
  23465. return 1;
  23466. },
  23467. enumerable: true,
  23468. configurable: true
  23469. });
  23470. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23471. get: function () {
  23472. return 2;
  23473. },
  23474. enumerable: true,
  23475. configurable: true
  23476. });
  23477. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23478. get: function () {
  23479. return 3;
  23480. },
  23481. enumerable: true,
  23482. configurable: true
  23483. });
  23484. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23485. get: function () {
  23486. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23487. },
  23488. set: function (value) {
  23489. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23495. get: function () {
  23496. return SceneLoader._ShowLoadingScreen;
  23497. },
  23498. set: function (value) {
  23499. SceneLoader._ShowLoadingScreen = value;
  23500. },
  23501. enumerable: true,
  23502. configurable: true
  23503. });
  23504. Object.defineProperty(SceneLoader, "loggingLevel", {
  23505. get: function () {
  23506. return SceneLoader._loggingLevel;
  23507. },
  23508. set: function (value) {
  23509. SceneLoader._loggingLevel = value;
  23510. },
  23511. enumerable: true,
  23512. configurable: true
  23513. });
  23514. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23515. var dotPosition = sceneFilename.lastIndexOf(".");
  23516. var queryStringPosition = sceneFilename.indexOf("?");
  23517. if (queryStringPosition === -1) {
  23518. queryStringPosition = sceneFilename.length;
  23519. }
  23520. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23521. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23522. var plugin = this._registeredPlugins[index];
  23523. if (plugin.extensions.indexOf(extension) !== -1) {
  23524. return plugin;
  23525. }
  23526. }
  23527. return this._registeredPlugins[this._registeredPlugins.length - 1];
  23528. };
  23529. // Public functions
  23530. SceneLoader.GetPluginForExtension = function (extension) {
  23531. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23532. var plugin = this._registeredPlugins[index];
  23533. if (plugin.extensions.indexOf(extension) !== -1) {
  23534. return plugin;
  23535. }
  23536. }
  23537. return null;
  23538. };
  23539. SceneLoader.RegisterPlugin = function (plugin) {
  23540. plugin.extensions = plugin.extensions.toLowerCase();
  23541. SceneLoader._registeredPlugins.push(plugin);
  23542. };
  23543. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23544. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23545. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23546. return;
  23547. }
  23548. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23549. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23550. return;
  23551. }
  23552. var loadingToken = {};
  23553. scene._addPendingData(loadingToken);
  23554. var manifestChecked = function (success) {
  23555. scene.database = database;
  23556. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23557. var importMeshFromData = function (data) {
  23558. var meshes = [];
  23559. var particleSystems = [];
  23560. var skeletons = [];
  23561. try {
  23562. if (plugin.importMesh) {
  23563. var syncedPlugin = plugin;
  23564. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23565. if (onerror) {
  23566. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23567. }
  23568. scene._removePendingData(loadingToken);
  23569. return;
  23570. }
  23571. if (onsuccess) {
  23572. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23573. onsuccess(meshes, particleSystems, skeletons);
  23574. scene._removePendingData(loadingToken);
  23575. }
  23576. }
  23577. else {
  23578. var asyncedPlugin = plugin;
  23579. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23580. if (onsuccess) {
  23581. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23582. onsuccess(meshes, particleSystems, skeletons);
  23583. scene._removePendingData(loadingToken);
  23584. }
  23585. }, function () {
  23586. if (onerror) {
  23587. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23588. }
  23589. scene._removePendingData(loadingToken);
  23590. });
  23591. }
  23592. }
  23593. catch (e) {
  23594. if (onerror) {
  23595. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  23596. }
  23597. scene._removePendingData(loadingToken);
  23598. }
  23599. };
  23600. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23601. // Direct load
  23602. importMeshFromData(sceneFilename.substr(5));
  23603. return;
  23604. }
  23605. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23606. importMeshFromData(data);
  23607. }, progressCallBack, database);
  23608. };
  23609. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23610. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23611. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23612. }
  23613. else {
  23614. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23615. manifestChecked(true);
  23616. }
  23617. };
  23618. /**
  23619. * Load a scene
  23620. * @param rootUrl a string that defines the root url for scene and resources
  23621. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23622. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23623. */
  23624. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23625. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23626. };
  23627. /**
  23628. * Append a scene
  23629. * @param rootUrl a string that defines the root url for scene and resources
  23630. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23631. * @param scene is the instance of BABYLON.Scene to append to
  23632. */
  23633. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23634. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23635. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23636. return;
  23637. }
  23638. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23639. var database;
  23640. var loadingToken = {};
  23641. scene._addPendingData(loadingToken);
  23642. if (SceneLoader.ShowLoadingScreen) {
  23643. scene.getEngine().displayLoadingUI();
  23644. }
  23645. var loadSceneFromData = function (data) {
  23646. scene.database = database;
  23647. if (plugin.load) {
  23648. var syncedPlugin = plugin;
  23649. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23650. if (onerror) {
  23651. onerror(scene);
  23652. }
  23653. scene._removePendingData(loadingToken);
  23654. scene.getEngine().hideLoadingUI();
  23655. return;
  23656. }
  23657. if (onsuccess) {
  23658. onsuccess(scene);
  23659. }
  23660. scene._removePendingData(loadingToken);
  23661. }
  23662. else {
  23663. var asyncedPlugin = plugin;
  23664. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23665. if (onsuccess) {
  23666. onsuccess(scene);
  23667. }
  23668. }, function () {
  23669. if (onerror) {
  23670. onerror(scene);
  23671. }
  23672. scene._removePendingData(loadingToken);
  23673. scene.getEngine().hideLoadingUI();
  23674. });
  23675. }
  23676. if (SceneLoader.ShowLoadingScreen) {
  23677. scene.executeWhenReady(function () {
  23678. scene.getEngine().hideLoadingUI();
  23679. });
  23680. }
  23681. };
  23682. var manifestChecked = function (success) {
  23683. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23684. };
  23685. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23686. // Direct load
  23687. loadSceneFromData(sceneFilename.substr(5));
  23688. return;
  23689. }
  23690. if (rootUrl.indexOf("file:") === -1) {
  23691. if (scene.getEngine().enableOfflineSupport) {
  23692. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23693. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23694. }
  23695. else {
  23696. manifestChecked(true);
  23697. }
  23698. }
  23699. else {
  23700. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23701. }
  23702. };
  23703. // Flags
  23704. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23705. SceneLoader._ShowLoadingScreen = true;
  23706. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23707. // Members
  23708. SceneLoader._registeredPlugins = new Array();
  23709. return SceneLoader;
  23710. })();
  23711. BABYLON.SceneLoader = SceneLoader;
  23712. ;
  23713. })(BABYLON || (BABYLON = {}));
  23714. var BABYLON;
  23715. (function (BABYLON) {
  23716. var Internals;
  23717. (function (Internals) {
  23718. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23719. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23720. var parsedMaterial = parsedData.materials[index];
  23721. if (parsedMaterial.id === id) {
  23722. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23723. }
  23724. }
  23725. return null;
  23726. };
  23727. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23728. names = (names instanceof Array) ? names : [names];
  23729. for (var i in names) {
  23730. if (mesh.name === names[i]) {
  23731. hierarchyIds.push(mesh.id);
  23732. return true;
  23733. }
  23734. }
  23735. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23736. hierarchyIds.push(mesh.id);
  23737. return true;
  23738. }
  23739. return false;
  23740. };
  23741. var logOperation = function (operation, producer) {
  23742. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23743. };
  23744. BABYLON.SceneLoader.RegisterPlugin({
  23745. extensions: ".babylon",
  23746. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23747. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23748. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23749. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23750. // and avoid problems with multiple concurrent .babylon loads.
  23751. var log = "importMesh has failed JSON parse";
  23752. try {
  23753. var parsedData = JSON.parse(data);
  23754. log = "";
  23755. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23756. var loadedSkeletonsIds = [];
  23757. var loadedMaterialsIds = [];
  23758. var hierarchyIds = [];
  23759. var index;
  23760. var cache;
  23761. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23762. var parsedMesh = parsedData.meshes[index];
  23763. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23764. if (meshesNames instanceof Array) {
  23765. // Remove found mesh name from list.
  23766. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23767. }
  23768. //Geometry?
  23769. if (parsedMesh.geometryId) {
  23770. //does the file contain geometries?
  23771. if (parsedData.geometries) {
  23772. //find the correct geometry and add it to the scene
  23773. var found = false;
  23774. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23775. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23776. return;
  23777. }
  23778. else {
  23779. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23780. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23781. switch (geometryType) {
  23782. case "boxes":
  23783. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23784. break;
  23785. case "spheres":
  23786. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23787. break;
  23788. case "cylinders":
  23789. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23790. break;
  23791. case "toruses":
  23792. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23793. break;
  23794. case "grounds":
  23795. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23796. break;
  23797. case "planes":
  23798. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23799. break;
  23800. case "torusKnots":
  23801. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23802. break;
  23803. case "vertexData":
  23804. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23805. break;
  23806. }
  23807. found = true;
  23808. }
  23809. });
  23810. }
  23811. });
  23812. if (!found) {
  23813. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  23814. }
  23815. }
  23816. }
  23817. // Material ?
  23818. if (parsedMesh.materialId) {
  23819. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  23820. if (!materialFound && parsedData.multiMaterials) {
  23821. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  23822. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  23823. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  23824. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  23825. var subMatId = parsedMultiMaterial.materials[matIndex];
  23826. loadedMaterialsIds.push(subMatId);
  23827. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  23828. log += "\n\tMaterial " + mat.toString(fullDetails);
  23829. }
  23830. loadedMaterialsIds.push(parsedMultiMaterial.id);
  23831. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23832. materialFound = true;
  23833. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  23834. break;
  23835. }
  23836. }
  23837. }
  23838. if (!materialFound) {
  23839. loadedMaterialsIds.push(parsedMesh.materialId);
  23840. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  23841. if (!mat) {
  23842. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  23843. }
  23844. else {
  23845. log += "\n\tMaterial " + mat.toString(fullDetails);
  23846. }
  23847. }
  23848. }
  23849. // Skeleton ?
  23850. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  23851. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  23852. if (!skeletonAlreadyLoaded) {
  23853. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  23854. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  23855. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  23856. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23857. skeletons.push(skeleton);
  23858. loadedSkeletonsIds.push(parsedSkeleton.id);
  23859. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  23860. }
  23861. }
  23862. }
  23863. }
  23864. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23865. meshes.push(mesh);
  23866. log += "\n\tMesh " + mesh.toString(fullDetails);
  23867. }
  23868. }
  23869. // Connecting parents
  23870. var currentMesh;
  23871. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23872. currentMesh = scene.meshes[index];
  23873. if (currentMesh._waitingParentId) {
  23874. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  23875. currentMesh._waitingParentId = undefined;
  23876. }
  23877. }
  23878. // freeze and compute world matrix application
  23879. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23880. currentMesh = scene.meshes[index];
  23881. if (currentMesh._waitingFreezeWorldMatrix) {
  23882. currentMesh.freezeWorldMatrix();
  23883. currentMesh._waitingFreezeWorldMatrix = undefined;
  23884. }
  23885. else {
  23886. currentMesh.computeWorldMatrix(true);
  23887. }
  23888. }
  23889. // Particles
  23890. if (parsedData.particleSystems) {
  23891. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  23892. var parsedParticleSystem = parsedData.particleSystems[index];
  23893. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  23894. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  23895. }
  23896. }
  23897. }
  23898. return true;
  23899. }
  23900. catch (err) {
  23901. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  23902. log = null;
  23903. throw err;
  23904. }
  23905. finally {
  23906. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  23907. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  23908. }
  23909. }
  23910. },
  23911. load: function (scene, data, rootUrl) {
  23912. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23913. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23914. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23915. // and avoid problems with multiple concurrent .babylon loads.
  23916. var log = "importScene has failed JSON parse";
  23917. try {
  23918. var parsedData = JSON.parse(data);
  23919. log = "";
  23920. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23921. // Scene
  23922. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  23923. scene.autoClear = parsedData.autoClear;
  23924. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  23925. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  23926. if (parsedData.gravity) {
  23927. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  23928. }
  23929. // Fog
  23930. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  23931. scene.fogMode = parsedData.fogMode;
  23932. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  23933. scene.fogStart = parsedData.fogStart;
  23934. scene.fogEnd = parsedData.fogEnd;
  23935. scene.fogDensity = parsedData.fogDensity;
  23936. log += "\tFog mode for scene: ";
  23937. switch (scene.fogMode) {
  23938. // getters not compiling, so using hardcoded
  23939. case 1:
  23940. log += "exp\n";
  23941. break;
  23942. case 2:
  23943. log += "exp2\n";
  23944. break;
  23945. case 3:
  23946. log += "linear\n";
  23947. break;
  23948. }
  23949. }
  23950. //Physics
  23951. if (parsedData.physicsEnabled) {
  23952. var physicsPlugin;
  23953. if (parsedData.physicsEngine === "cannon") {
  23954. physicsPlugin = new BABYLON.CannonJSPlugin();
  23955. }
  23956. else if (parsedData.physicsEngine === "oimo") {
  23957. physicsPlugin = new BABYLON.OimoJSPlugin();
  23958. }
  23959. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  23960. //else - default engine, which is currently oimo
  23961. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  23962. scene.enablePhysics(physicsGravity, physicsPlugin);
  23963. }
  23964. //collisions, if defined. otherwise, default is true
  23965. if (parsedData.collisionsEnabled != undefined) {
  23966. scene.collisionsEnabled = parsedData.collisionsEnabled;
  23967. }
  23968. scene.workerCollisions = !!parsedData.workerCollisions;
  23969. var index;
  23970. var cache;
  23971. // Lights
  23972. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  23973. var parsedLight = parsedData.lights[index];
  23974. var light = BABYLON.Light.Parse(parsedLight, scene);
  23975. log += (index === 0 ? "\n\tLights:" : "");
  23976. log += "\n\t\t" + light.toString(fullDetails);
  23977. }
  23978. // Animations
  23979. if (parsedData.animations) {
  23980. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  23981. var parsedAnimation = parsedData.animations[index];
  23982. var animation = BABYLON.Animation.Parse(parsedAnimation);
  23983. scene.animations.push(animation);
  23984. log += (index === 0 ? "\n\tAnimations:" : "");
  23985. log += "\n\t\t" + animation.toString(fullDetails);
  23986. }
  23987. }
  23988. // Materials
  23989. if (parsedData.materials) {
  23990. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23991. var parsedMaterial = parsedData.materials[index];
  23992. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23993. log += (index === 0 ? "\n\tMaterials:" : "");
  23994. log += "\n\t\t" + mat.toString(fullDetails);
  23995. }
  23996. }
  23997. if (parsedData.multiMaterials) {
  23998. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  23999. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24000. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24001. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24002. log += "\n\t\t" + mmat.toString(fullDetails);
  24003. }
  24004. }
  24005. // Skeletons
  24006. if (parsedData.skeletons) {
  24007. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24008. var parsedSkeleton = parsedData.skeletons[index];
  24009. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24010. log += (index === 0 ? "\n\tSkeletons:" : "");
  24011. log += "\n\t\t" + skeleton.toString(fullDetails);
  24012. }
  24013. }
  24014. // Geometries
  24015. var geometries = parsedData.geometries;
  24016. if (geometries) {
  24017. // Boxes
  24018. var boxes = geometries.boxes;
  24019. if (boxes) {
  24020. for (index = 0, cache = boxes.length; index < cache; index++) {
  24021. var parsedBox = boxes[index];
  24022. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24023. }
  24024. }
  24025. // Spheres
  24026. var spheres = geometries.spheres;
  24027. if (spheres) {
  24028. for (index = 0, cache = spheres.length; index < cache; index++) {
  24029. var parsedSphere = spheres[index];
  24030. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24031. }
  24032. }
  24033. // Cylinders
  24034. var cylinders = geometries.cylinders;
  24035. if (cylinders) {
  24036. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24037. var parsedCylinder = cylinders[index];
  24038. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24039. }
  24040. }
  24041. // Toruses
  24042. var toruses = geometries.toruses;
  24043. if (toruses) {
  24044. for (index = 0, cache = toruses.length; index < cache; index++) {
  24045. var parsedTorus = toruses[index];
  24046. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24047. }
  24048. }
  24049. // Grounds
  24050. var grounds = geometries.grounds;
  24051. if (grounds) {
  24052. for (index = 0, cache = grounds.length; index < cache; index++) {
  24053. var parsedGround = grounds[index];
  24054. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24055. }
  24056. }
  24057. // Planes
  24058. var planes = geometries.planes;
  24059. if (planes) {
  24060. for (index = 0, cache = planes.length; index < cache; index++) {
  24061. var parsedPlane = planes[index];
  24062. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24063. }
  24064. }
  24065. // TorusKnots
  24066. var torusKnots = geometries.torusKnots;
  24067. if (torusKnots) {
  24068. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24069. var parsedTorusKnot = torusKnots[index];
  24070. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24071. }
  24072. }
  24073. // VertexData
  24074. var vertexData = geometries.vertexData;
  24075. if (vertexData) {
  24076. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24077. var parsedVertexData = vertexData[index];
  24078. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24079. }
  24080. }
  24081. }
  24082. // Meshes
  24083. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24084. var parsedMesh = parsedData.meshes[index];
  24085. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24086. log += (index === 0 ? "\n\tMeshes:" : "");
  24087. log += "\n\t\t" + mesh.toString(fullDetails);
  24088. }
  24089. // Cameras
  24090. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24091. var parsedCamera = parsedData.cameras[index];
  24092. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24093. log += (index === 0 ? "\n\tCameras:" : "");
  24094. log += "\n\t\t" + camera.toString(fullDetails);
  24095. }
  24096. if (parsedData.activeCameraID) {
  24097. scene.setActiveCameraByID(parsedData.activeCameraID);
  24098. }
  24099. // Browsing all the graph to connect the dots
  24100. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24101. var camera = scene.cameras[index];
  24102. if (camera._waitingParentId) {
  24103. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24104. camera._waitingParentId = undefined;
  24105. }
  24106. }
  24107. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24108. var light = scene.lights[index];
  24109. if (light._waitingParentId) {
  24110. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24111. light._waitingParentId = undefined;
  24112. }
  24113. }
  24114. // Sounds
  24115. var loadedSounds = [];
  24116. var loadedSound;
  24117. if (BABYLON.AudioEngine && parsedData.sounds) {
  24118. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24119. var parsedSound = parsedData.sounds[index];
  24120. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24121. if (!parsedSound.url)
  24122. parsedSound.url = parsedSound.name;
  24123. if (!loadedSounds[parsedSound.url]) {
  24124. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24125. loadedSounds[parsedSound.url] = loadedSound;
  24126. }
  24127. else {
  24128. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24129. }
  24130. }
  24131. else {
  24132. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24133. }
  24134. }
  24135. }
  24136. loadedSounds = [];
  24137. // Connect parents & children and parse actions
  24138. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24139. var mesh = scene.meshes[index];
  24140. if (mesh._waitingParentId) {
  24141. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24142. mesh._waitingParentId = undefined;
  24143. }
  24144. if (mesh._waitingActions) {
  24145. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24146. mesh._waitingActions = undefined;
  24147. }
  24148. }
  24149. // freeze world matrix application
  24150. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24151. var currentMesh = scene.meshes[index];
  24152. if (currentMesh._waitingFreezeWorldMatrix) {
  24153. currentMesh.freezeWorldMatrix();
  24154. currentMesh._waitingFreezeWorldMatrix = undefined;
  24155. }
  24156. else {
  24157. currentMesh.computeWorldMatrix(true);
  24158. }
  24159. }
  24160. // Particles Systems
  24161. if (parsedData.particleSystems) {
  24162. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24163. var parsedParticleSystem = parsedData.particleSystems[index];
  24164. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24165. }
  24166. }
  24167. // Lens flares
  24168. if (parsedData.lensFlareSystems) {
  24169. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24170. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24171. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24172. }
  24173. }
  24174. // Shadows
  24175. if (parsedData.shadowGenerators) {
  24176. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24177. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24178. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24179. }
  24180. }
  24181. // Actions (scene)
  24182. if (parsedData.actions) {
  24183. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24184. }
  24185. // Finish
  24186. return true;
  24187. }
  24188. catch (err) {
  24189. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24190. log = null;
  24191. throw err;
  24192. }
  24193. finally {
  24194. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24195. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24196. }
  24197. }
  24198. }
  24199. });
  24200. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24201. })(BABYLON || (BABYLON = {}));
  24202. var BABYLON;
  24203. (function (BABYLON) {
  24204. var SpriteManager = (function () {
  24205. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24207. this.name = name;
  24208. this.cellSize = cellSize;
  24209. this.sprites = new Array();
  24210. this.renderingGroupId = 0;
  24211. this.layerMask = 0x0FFFFFFF;
  24212. this.fogEnabled = true;
  24213. this.isPickable = false;
  24214. this._vertexDeclaration = [4, 4, 4, 4];
  24215. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24216. this._capacity = capacity;
  24217. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24218. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24219. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24220. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24221. this._scene = scene;
  24222. this._scene.spriteManagers.push(this);
  24223. // VBO
  24224. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24225. var indices = [];
  24226. var index = 0;
  24227. for (var count = 0; count < capacity; count++) {
  24228. indices.push(index);
  24229. indices.push(index + 1);
  24230. indices.push(index + 2);
  24231. indices.push(index);
  24232. indices.push(index + 2);
  24233. indices.push(index + 3);
  24234. index += 4;
  24235. }
  24236. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24237. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24238. // Effects
  24239. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24240. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24241. }
  24242. Object.defineProperty(SpriteManager.prototype, "texture", {
  24243. get: function () {
  24244. return this._spriteTexture;
  24245. },
  24246. set: function (value) {
  24247. this._spriteTexture = value;
  24248. },
  24249. enumerable: true,
  24250. configurable: true
  24251. });
  24252. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24253. var arrayOffset = index * 16;
  24254. if (offsetX === 0)
  24255. offsetX = this._epsilon;
  24256. else if (offsetX === 1)
  24257. offsetX = 1 - this._epsilon;
  24258. if (offsetY === 0)
  24259. offsetY = this._epsilon;
  24260. else if (offsetY === 1)
  24261. offsetY = 1 - this._epsilon;
  24262. this._vertices[arrayOffset] = sprite.position.x;
  24263. this._vertices[arrayOffset + 1] = sprite.position.y;
  24264. this._vertices[arrayOffset + 2] = sprite.position.z;
  24265. this._vertices[arrayOffset + 3] = sprite.angle;
  24266. this._vertices[arrayOffset + 4] = sprite.width;
  24267. this._vertices[arrayOffset + 5] = sprite.height;
  24268. this._vertices[arrayOffset + 6] = offsetX;
  24269. this._vertices[arrayOffset + 7] = offsetY;
  24270. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24271. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24272. var offset = (sprite.cellIndex / rowSize) >> 0;
  24273. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24274. this._vertices[arrayOffset + 11] = offset;
  24275. // Color
  24276. this._vertices[arrayOffset + 12] = sprite.color.r;
  24277. this._vertices[arrayOffset + 13] = sprite.color.g;
  24278. this._vertices[arrayOffset + 14] = sprite.color.b;
  24279. this._vertices[arrayOffset + 15] = sprite.color.a;
  24280. };
  24281. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24282. var count = Math.min(this._capacity, this.sprites.length);
  24283. var min = BABYLON.Vector3.Zero();
  24284. var max = BABYLON.Vector3.Zero();
  24285. var distance = Number.MAX_VALUE;
  24286. var currentSprite;
  24287. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24288. var cameraView = camera.getViewMatrix();
  24289. for (var index = 0; index < count; index++) {
  24290. var sprite = this.sprites[index];
  24291. if (!sprite) {
  24292. continue;
  24293. }
  24294. if (predicate) {
  24295. if (!predicate(sprite)) {
  24296. continue;
  24297. }
  24298. }
  24299. else if (!sprite.isPickable) {
  24300. continue;
  24301. }
  24302. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24303. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24304. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24305. if (ray.intersectsBoxMinMax(min, max)) {
  24306. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24307. if (distance > currentDistance) {
  24308. distance = currentDistance;
  24309. currentSprite = sprite;
  24310. if (fastCheck) {
  24311. break;
  24312. }
  24313. }
  24314. }
  24315. }
  24316. if (currentSprite) {
  24317. var result = new BABYLON.PickingInfo();
  24318. result.hit = true;
  24319. result.pickedSprite = currentSprite;
  24320. result.distance = distance;
  24321. return result;
  24322. }
  24323. return null;
  24324. };
  24325. SpriteManager.prototype.render = function () {
  24326. // Check
  24327. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24328. return;
  24329. var engine = this._scene.getEngine();
  24330. var baseSize = this._spriteTexture.getBaseSize();
  24331. // Sprites
  24332. var deltaTime = engine.getDeltaTime();
  24333. var max = Math.min(this._capacity, this.sprites.length);
  24334. var rowSize = baseSize.width / this.cellSize;
  24335. var offset = 0;
  24336. for (var index = 0; index < max; index++) {
  24337. var sprite = this.sprites[index];
  24338. if (!sprite) {
  24339. continue;
  24340. }
  24341. sprite._animate(deltaTime);
  24342. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24343. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24344. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24345. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24346. }
  24347. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24348. // Render
  24349. var effect = this._effectBase;
  24350. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24351. effect = this._effectFog;
  24352. }
  24353. engine.enableEffect(effect);
  24354. var viewMatrix = this._scene.getViewMatrix();
  24355. effect.setTexture("diffuseSampler", this._spriteTexture);
  24356. effect.setMatrix("view", viewMatrix);
  24357. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24358. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24359. // Fog
  24360. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24361. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24362. effect.setColor3("vFogColor", this._scene.fogColor);
  24363. }
  24364. // VBOs
  24365. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24366. // Draw order
  24367. engine.setDepthFunctionToLessOrEqual();
  24368. effect.setBool("alphaTest", true);
  24369. engine.setColorWrite(false);
  24370. engine.draw(true, 0, max * 6);
  24371. engine.setColorWrite(true);
  24372. effect.setBool("alphaTest", false);
  24373. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24374. engine.draw(true, 0, max * 6);
  24375. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24376. };
  24377. SpriteManager.prototype.dispose = function () {
  24378. if (this._vertexBuffer) {
  24379. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24380. this._vertexBuffer = null;
  24381. }
  24382. if (this._indexBuffer) {
  24383. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24384. this._indexBuffer = null;
  24385. }
  24386. if (this._spriteTexture) {
  24387. this._spriteTexture.dispose();
  24388. this._spriteTexture = null;
  24389. }
  24390. // Remove from scene
  24391. var index = this._scene.spriteManagers.indexOf(this);
  24392. this._scene.spriteManagers.splice(index, 1);
  24393. // Callback
  24394. if (this.onDispose) {
  24395. this.onDispose();
  24396. }
  24397. };
  24398. return SpriteManager;
  24399. })();
  24400. BABYLON.SpriteManager = SpriteManager;
  24401. })(BABYLON || (BABYLON = {}));
  24402. var BABYLON;
  24403. (function (BABYLON) {
  24404. var Sprite = (function () {
  24405. function Sprite(name, manager) {
  24406. this.name = name;
  24407. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24408. this.width = 1.0;
  24409. this.height = 1.0;
  24410. this.angle = 0;
  24411. this.cellIndex = 0;
  24412. this.invertU = 0;
  24413. this.invertV = 0;
  24414. this.animations = new Array();
  24415. this.isPickable = false;
  24416. this._animationStarted = false;
  24417. this._loopAnimation = false;
  24418. this._fromIndex = 0;
  24419. this._toIndex = 0;
  24420. this._delay = 0;
  24421. this._direction = 1;
  24422. this._frameCount = 0;
  24423. this._time = 0;
  24424. this._manager = manager;
  24425. this._manager.sprites.push(this);
  24426. this.position = BABYLON.Vector3.Zero();
  24427. }
  24428. Object.defineProperty(Sprite.prototype, "size", {
  24429. get: function () {
  24430. return this.width;
  24431. },
  24432. set: function (value) {
  24433. this.width = value;
  24434. this.height = value;
  24435. },
  24436. enumerable: true,
  24437. configurable: true
  24438. });
  24439. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24440. this._fromIndex = from;
  24441. this._toIndex = to;
  24442. this._loopAnimation = loop;
  24443. this._delay = delay;
  24444. this._animationStarted = true;
  24445. this._direction = from < to ? 1 : -1;
  24446. this.cellIndex = from;
  24447. this._time = 0;
  24448. };
  24449. Sprite.prototype.stopAnimation = function () {
  24450. this._animationStarted = false;
  24451. };
  24452. Sprite.prototype._animate = function (deltaTime) {
  24453. if (!this._animationStarted)
  24454. return;
  24455. this._time += deltaTime;
  24456. if (this._time > this._delay) {
  24457. this._time = this._time % this._delay;
  24458. this.cellIndex += this._direction;
  24459. if (this.cellIndex == this._toIndex) {
  24460. if (this._loopAnimation) {
  24461. this.cellIndex = this._fromIndex;
  24462. }
  24463. else {
  24464. this._animationStarted = false;
  24465. if (this.disposeWhenFinishedAnimating) {
  24466. this.dispose();
  24467. }
  24468. }
  24469. }
  24470. }
  24471. };
  24472. Sprite.prototype.dispose = function () {
  24473. for (var i = 0; i < this._manager.sprites.length; i++) {
  24474. if (this._manager.sprites[i] == this) {
  24475. this._manager.sprites.splice(i, 1);
  24476. }
  24477. }
  24478. };
  24479. return Sprite;
  24480. })();
  24481. BABYLON.Sprite = Sprite;
  24482. })(BABYLON || (BABYLON = {}));
  24483. var BABYLON;
  24484. (function (BABYLON) {
  24485. var Layer = (function () {
  24486. function Layer(name, imgUrl, scene, isBackground, color) {
  24487. this.name = name;
  24488. this.scale = new BABYLON.Vector2(1, 1);
  24489. this.offset = new BABYLON.Vector2(0, 0);
  24490. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24491. this._vertexDeclaration = [2];
  24492. this._vertexStrideSize = 2 * 4;
  24493. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24494. this.isBackground = isBackground === undefined ? true : isBackground;
  24495. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24496. this._scene = scene;
  24497. this._scene.layers.push(this);
  24498. // VBO
  24499. var vertices = [];
  24500. vertices.push(1, 1);
  24501. vertices.push(-1, 1);
  24502. vertices.push(-1, -1);
  24503. vertices.push(1, -1);
  24504. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24505. // Indices
  24506. var indices = [];
  24507. indices.push(0);
  24508. indices.push(1);
  24509. indices.push(2);
  24510. indices.push(0);
  24511. indices.push(2);
  24512. indices.push(3);
  24513. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24514. // Effects
  24515. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24516. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24517. }
  24518. Layer.prototype.render = function () {
  24519. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24520. // Check
  24521. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24522. return;
  24523. var engine = this._scene.getEngine();
  24524. if (this.onBeforeRender) {
  24525. this.onBeforeRender();
  24526. }
  24527. // Render
  24528. engine.enableEffect(currentEffect);
  24529. engine.setState(false);
  24530. // Texture
  24531. currentEffect.setTexture("textureSampler", this.texture);
  24532. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24533. // Color
  24534. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24535. // Scale / offset
  24536. currentEffect.setVector2("offset", this.offset);
  24537. currentEffect.setVector2("scale", this.scale);
  24538. // VBOs
  24539. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24540. // Draw order
  24541. if (!this._alphaTestEffect) {
  24542. engine.setAlphaMode(this.alphaBlendingMode);
  24543. engine.draw(true, 0, 6);
  24544. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24545. }
  24546. else {
  24547. engine.draw(true, 0, 6);
  24548. }
  24549. if (this.onAfterRender) {
  24550. this.onAfterRender();
  24551. }
  24552. };
  24553. Layer.prototype.dispose = function () {
  24554. if (this._vertexBuffer) {
  24555. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24556. this._vertexBuffer = null;
  24557. }
  24558. if (this._indexBuffer) {
  24559. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24560. this._indexBuffer = null;
  24561. }
  24562. if (this.texture) {
  24563. this.texture.dispose();
  24564. this.texture = null;
  24565. }
  24566. // Remove from scene
  24567. var index = this._scene.layers.indexOf(this);
  24568. this._scene.layers.splice(index, 1);
  24569. // Callback
  24570. if (this.onDispose) {
  24571. this.onDispose();
  24572. }
  24573. };
  24574. return Layer;
  24575. })();
  24576. BABYLON.Layer = Layer;
  24577. })(BABYLON || (BABYLON = {}));
  24578. var BABYLON;
  24579. (function (BABYLON) {
  24580. var Particle = (function () {
  24581. function Particle() {
  24582. this.position = BABYLON.Vector3.Zero();
  24583. this.direction = BABYLON.Vector3.Zero();
  24584. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24585. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24586. this.lifeTime = 1.0;
  24587. this.age = 0;
  24588. this.size = 0;
  24589. this.angle = 0;
  24590. this.angularSpeed = 0;
  24591. }
  24592. Particle.prototype.copyTo = function (other) {
  24593. other.position.copyFrom(this.position);
  24594. other.direction.copyFrom(this.direction);
  24595. other.color.copyFrom(this.color);
  24596. other.colorStep.copyFrom(this.colorStep);
  24597. other.lifeTime = this.lifeTime;
  24598. other.age = this.age;
  24599. other.size = this.size;
  24600. other.angle = this.angle;
  24601. other.angularSpeed = this.angularSpeed;
  24602. };
  24603. return Particle;
  24604. })();
  24605. BABYLON.Particle = Particle;
  24606. })(BABYLON || (BABYLON = {}));
  24607. var BABYLON;
  24608. (function (BABYLON) {
  24609. var randomNumber = function (min, max) {
  24610. if (min === max) {
  24611. return (min);
  24612. }
  24613. var random = Math.random();
  24614. return ((random * (max - min)) + min);
  24615. };
  24616. var ParticleSystem = (function () {
  24617. function ParticleSystem(name, capacity, scene, customEffect) {
  24618. var _this = this;
  24619. this.name = name;
  24620. // Members
  24621. this.animations = [];
  24622. this.renderingGroupId = 0;
  24623. this.emitter = null;
  24624. this.emitRate = 10;
  24625. this.manualEmitCount = -1;
  24626. this.updateSpeed = 0.01;
  24627. this.targetStopDuration = 0;
  24628. this.disposeOnStop = false;
  24629. this.minEmitPower = 1;
  24630. this.maxEmitPower = 1;
  24631. this.minLifeTime = 1;
  24632. this.maxLifeTime = 1;
  24633. this.minSize = 1;
  24634. this.maxSize = 1;
  24635. this.minAngularSpeed = 0;
  24636. this.maxAngularSpeed = 0;
  24637. this.layerMask = 0x0FFFFFFF;
  24638. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24639. this.forceDepthWrite = false;
  24640. this.gravity = BABYLON.Vector3.Zero();
  24641. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24642. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24643. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24644. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24645. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24646. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24647. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24648. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24649. this.particles = new Array();
  24650. this._vertexDeclaration = [3, 4, 4];
  24651. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24652. this._stockParticles = new Array();
  24653. this._newPartsExcess = 0;
  24654. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24655. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24656. this._scaledDirection = BABYLON.Vector3.Zero();
  24657. this._scaledGravity = BABYLON.Vector3.Zero();
  24658. this._currentRenderId = -1;
  24659. this._started = false;
  24660. this._stopped = false;
  24661. this._actualFrame = 0;
  24662. this.id = name;
  24663. this._capacity = capacity;
  24664. this._scene = scene;
  24665. this._customEffect = customEffect;
  24666. scene.particleSystems.push(this);
  24667. // VBO
  24668. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24669. var indices = [];
  24670. var index = 0;
  24671. for (var count = 0; count < capacity; count++) {
  24672. indices.push(index);
  24673. indices.push(index + 1);
  24674. indices.push(index + 2);
  24675. indices.push(index);
  24676. indices.push(index + 2);
  24677. indices.push(index + 3);
  24678. index += 4;
  24679. }
  24680. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24681. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24682. // Default behaviors
  24683. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24684. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24685. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24686. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24687. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24688. };
  24689. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24690. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24691. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24692. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24693. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24694. };
  24695. this.updateFunction = function (particles) {
  24696. for (var index = 0; index < particles.length; index++) {
  24697. var particle = particles[index];
  24698. particle.age += _this._scaledUpdateSpeed;
  24699. if (particle.age >= particle.lifeTime) {
  24700. _this.recycleParticle(particle);
  24701. index--;
  24702. continue;
  24703. }
  24704. else {
  24705. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24706. particle.color.addInPlace(_this._scaledColorStep);
  24707. if (particle.color.a < 0)
  24708. particle.color.a = 0;
  24709. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24710. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24711. particle.position.addInPlace(_this._scaledDirection);
  24712. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24713. particle.direction.addInPlace(_this._scaledGravity);
  24714. }
  24715. }
  24716. };
  24717. }
  24718. ParticleSystem.prototype.recycleParticle = function (particle) {
  24719. var lastParticle = this.particles.pop();
  24720. if (lastParticle !== particle) {
  24721. lastParticle.copyTo(particle);
  24722. this._stockParticles.push(lastParticle);
  24723. }
  24724. };
  24725. ParticleSystem.prototype.getCapacity = function () {
  24726. return this._capacity;
  24727. };
  24728. ParticleSystem.prototype.isAlive = function () {
  24729. return this._alive;
  24730. };
  24731. ParticleSystem.prototype.isStarted = function () {
  24732. return this._started;
  24733. };
  24734. ParticleSystem.prototype.start = function () {
  24735. this._started = true;
  24736. this._stopped = false;
  24737. this._actualFrame = 0;
  24738. };
  24739. ParticleSystem.prototype.stop = function () {
  24740. this._stopped = true;
  24741. };
  24742. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24743. var offset = index * 11;
  24744. this._vertices[offset] = particle.position.x;
  24745. this._vertices[offset + 1] = particle.position.y;
  24746. this._vertices[offset + 2] = particle.position.z;
  24747. this._vertices[offset + 3] = particle.color.r;
  24748. this._vertices[offset + 4] = particle.color.g;
  24749. this._vertices[offset + 5] = particle.color.b;
  24750. this._vertices[offset + 6] = particle.color.a;
  24751. this._vertices[offset + 7] = particle.angle;
  24752. this._vertices[offset + 8] = particle.size;
  24753. this._vertices[offset + 9] = offsetX;
  24754. this._vertices[offset + 10] = offsetY;
  24755. };
  24756. ParticleSystem.prototype._update = function (newParticles) {
  24757. // Update current
  24758. this._alive = this.particles.length > 0;
  24759. this.updateFunction(this.particles);
  24760. // Add new ones
  24761. var worldMatrix;
  24762. if (this.emitter.position) {
  24763. worldMatrix = this.emitter.getWorldMatrix();
  24764. }
  24765. else {
  24766. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24767. }
  24768. var particle;
  24769. for (var index = 0; index < newParticles; index++) {
  24770. if (this.particles.length === this._capacity) {
  24771. break;
  24772. }
  24773. if (this._stockParticles.length !== 0) {
  24774. particle = this._stockParticles.pop();
  24775. particle.age = 0;
  24776. }
  24777. else {
  24778. particle = new BABYLON.Particle();
  24779. }
  24780. this.particles.push(particle);
  24781. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24782. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24783. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24784. particle.size = randomNumber(this.minSize, this.maxSize);
  24785. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24786. this.startPositionFunction(worldMatrix, particle.position, particle);
  24787. var step = randomNumber(0, 1.0);
  24788. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24789. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24790. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24791. }
  24792. };
  24793. ParticleSystem.prototype._getEffect = function () {
  24794. if (this._customEffect) {
  24795. return this._customEffect;
  24796. }
  24797. ;
  24798. var defines = [];
  24799. if (this._scene.clipPlane) {
  24800. defines.push("#define CLIPPLANE");
  24801. }
  24802. // Effect
  24803. var join = defines.join("\n");
  24804. if (this._cachedDefines !== join) {
  24805. this._cachedDefines = join;
  24806. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  24807. }
  24808. return this._effect;
  24809. };
  24810. ParticleSystem.prototype.animate = function () {
  24811. if (!this._started)
  24812. return;
  24813. var effect = this._getEffect();
  24814. // Check
  24815. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  24816. return;
  24817. if (this._currentRenderId === this._scene.getRenderId()) {
  24818. return;
  24819. }
  24820. this._currentRenderId = this._scene.getRenderId();
  24821. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  24822. // determine the number of particles we need to create
  24823. var newParticles;
  24824. if (this.manualEmitCount > -1) {
  24825. newParticles = this.manualEmitCount;
  24826. this._newPartsExcess = 0;
  24827. this.manualEmitCount = 0;
  24828. }
  24829. else {
  24830. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  24831. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  24832. }
  24833. if (this._newPartsExcess > 1.0) {
  24834. newParticles += this._newPartsExcess >> 0;
  24835. this._newPartsExcess -= this._newPartsExcess >> 0;
  24836. }
  24837. this._alive = false;
  24838. if (!this._stopped) {
  24839. this._actualFrame += this._scaledUpdateSpeed;
  24840. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  24841. this.stop();
  24842. }
  24843. else {
  24844. newParticles = 0;
  24845. }
  24846. this._update(newParticles);
  24847. // Stopped?
  24848. if (this._stopped) {
  24849. if (!this._alive) {
  24850. this._started = false;
  24851. if (this.disposeOnStop) {
  24852. this._scene._toBeDisposed.push(this);
  24853. }
  24854. }
  24855. }
  24856. // Update VBO
  24857. var offset = 0;
  24858. for (var index = 0; index < this.particles.length; index++) {
  24859. var particle = this.particles[index];
  24860. this._appendParticleVertex(offset++, particle, 0, 0);
  24861. this._appendParticleVertex(offset++, particle, 1, 0);
  24862. this._appendParticleVertex(offset++, particle, 1, 1);
  24863. this._appendParticleVertex(offset++, particle, 0, 1);
  24864. }
  24865. var engine = this._scene.getEngine();
  24866. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24867. };
  24868. ParticleSystem.prototype.render = function () {
  24869. var effect = this._getEffect();
  24870. // Check
  24871. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  24872. return 0;
  24873. var engine = this._scene.getEngine();
  24874. // Render
  24875. engine.enableEffect(effect);
  24876. engine.setState(false);
  24877. var viewMatrix = this._scene.getViewMatrix();
  24878. effect.setTexture("diffuseSampler", this.particleTexture);
  24879. effect.setMatrix("view", viewMatrix);
  24880. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24881. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  24882. if (this._scene.clipPlane) {
  24883. var clipPlane = this._scene.clipPlane;
  24884. var invView = viewMatrix.clone();
  24885. invView.invert();
  24886. effect.setMatrix("invView", invView);
  24887. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24888. }
  24889. // VBOs
  24890. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24891. // Draw order
  24892. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  24893. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  24894. }
  24895. else {
  24896. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24897. }
  24898. if (this.forceDepthWrite) {
  24899. engine.setDepthWrite(true);
  24900. }
  24901. engine.draw(true, 0, this.particles.length * 6);
  24902. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24903. return this.particles.length;
  24904. };
  24905. ParticleSystem.prototype.dispose = function () {
  24906. if (this._vertexBuffer) {
  24907. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24908. this._vertexBuffer = null;
  24909. }
  24910. if (this._indexBuffer) {
  24911. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24912. this._indexBuffer = null;
  24913. }
  24914. if (this.particleTexture) {
  24915. this.particleTexture.dispose();
  24916. this.particleTexture = null;
  24917. }
  24918. // Remove from scene
  24919. var index = this._scene.particleSystems.indexOf(this);
  24920. this._scene.particleSystems.splice(index, 1);
  24921. // Callback
  24922. if (this.onDispose) {
  24923. this.onDispose();
  24924. }
  24925. };
  24926. // Clone
  24927. ParticleSystem.prototype.clone = function (name, newEmitter) {
  24928. var result = new ParticleSystem(name, this._capacity, this._scene);
  24929. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  24930. if (newEmitter === undefined) {
  24931. newEmitter = this.emitter;
  24932. }
  24933. result.emitter = newEmitter;
  24934. if (this.particleTexture) {
  24935. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  24936. }
  24937. result.start();
  24938. return result;
  24939. };
  24940. ParticleSystem.prototype.serialize = function () {
  24941. var serializationObject = {};
  24942. serializationObject.name = this.name;
  24943. serializationObject.id = this.id;
  24944. // Emitter
  24945. if (this.emitter.position) {
  24946. serializationObject.emitterId = this.emitter.id;
  24947. }
  24948. else {
  24949. serializationObject.emitter = this.emitter.asArray();
  24950. }
  24951. serializationObject.capacity = this.getCapacity();
  24952. if (this.particleTexture) {
  24953. serializationObject.textureName = this.particleTexture.name;
  24954. }
  24955. // Animations
  24956. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24957. // Particle system
  24958. serializationObject.minAngularSpeed = this.minAngularSpeed;
  24959. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  24960. serializationObject.minSize = this.minSize;
  24961. serializationObject.maxSize = this.maxSize;
  24962. serializationObject.minEmitPower = this.minEmitPower;
  24963. serializationObject.maxEmitPower = this.maxEmitPower;
  24964. serializationObject.minLifeTime = this.minLifeTime;
  24965. serializationObject.maxLifeTime = this.maxLifeTime;
  24966. serializationObject.emitRate = this.emitRate;
  24967. serializationObject.minEmitBox = this.minEmitBox.asArray();
  24968. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  24969. serializationObject.gravity = this.gravity.asArray();
  24970. serializationObject.direction1 = this.direction1.asArray();
  24971. serializationObject.direction2 = this.direction2.asArray();
  24972. serializationObject.color1 = this.color1.asArray();
  24973. serializationObject.color2 = this.color2.asArray();
  24974. serializationObject.colorDead = this.colorDead.asArray();
  24975. serializationObject.updateSpeed = this.updateSpeed;
  24976. serializationObject.targetStopDuration = this.targetStopDuration;
  24977. serializationObject.textureMask = this.textureMask.asArray();
  24978. serializationObject.blendMode = this.blendMode;
  24979. return serializationObject;
  24980. };
  24981. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  24982. var name = parsedParticleSystem.name;
  24983. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  24984. if (parsedParticleSystem.id) {
  24985. particleSystem.id = parsedParticleSystem.id;
  24986. }
  24987. // Texture
  24988. if (parsedParticleSystem.textureName) {
  24989. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  24990. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  24991. }
  24992. // Emitter
  24993. if (parsedParticleSystem.emitterId) {
  24994. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  24995. }
  24996. else {
  24997. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  24998. }
  24999. // Animations
  25000. if (parsedParticleSystem.animations) {
  25001. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  25002. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  25003. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25004. }
  25005. }
  25006. if (parsedParticleSystem.autoAnimate) {
  25007. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  25008. }
  25009. // Particle system
  25010. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  25011. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  25012. particleSystem.minSize = parsedParticleSystem.minSize;
  25013. particleSystem.maxSize = parsedParticleSystem.maxSize;
  25014. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  25015. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  25016. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  25017. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  25018. particleSystem.emitRate = parsedParticleSystem.emitRate;
  25019. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  25020. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  25021. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  25022. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  25023. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  25024. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  25025. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  25026. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  25027. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  25028. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  25029. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  25030. particleSystem.blendMode = parsedParticleSystem.blendMode;
  25031. if (!parsedParticleSystem.preventAutoStart) {
  25032. particleSystem.start();
  25033. }
  25034. return particleSystem;
  25035. };
  25036. // Statics
  25037. ParticleSystem.BLENDMODE_ONEONE = 0;
  25038. ParticleSystem.BLENDMODE_STANDARD = 1;
  25039. return ParticleSystem;
  25040. })();
  25041. BABYLON.ParticleSystem = ParticleSystem;
  25042. })(BABYLON || (BABYLON = {}));
  25043. var BABYLON;
  25044. (function (BABYLON) {
  25045. var AnimationRange = (function () {
  25046. function AnimationRange(name, from, to) {
  25047. this.name = name;
  25048. this.from = from;
  25049. this.to = to;
  25050. }
  25051. AnimationRange.prototype.clone = function () {
  25052. return new AnimationRange(this.name, this.from, this.to);
  25053. };
  25054. return AnimationRange;
  25055. })();
  25056. BABYLON.AnimationRange = AnimationRange;
  25057. /**
  25058. * Composed of a frame, and an action function
  25059. */
  25060. var AnimationEvent = (function () {
  25061. function AnimationEvent(frame, action, onlyOnce) {
  25062. this.frame = frame;
  25063. this.action = action;
  25064. this.onlyOnce = onlyOnce;
  25065. this.isDone = false;
  25066. }
  25067. return AnimationEvent;
  25068. })();
  25069. BABYLON.AnimationEvent = AnimationEvent;
  25070. var PathCursor = (function () {
  25071. function PathCursor(path) {
  25072. this.path = path;
  25073. this._onchange = new Array();
  25074. this.value = 0;
  25075. this.animations = new Array();
  25076. }
  25077. PathCursor.prototype.getPoint = function () {
  25078. var point = this.path.getPointAtLengthPosition(this.value);
  25079. return new BABYLON.Vector3(point.x, 0, point.y);
  25080. };
  25081. PathCursor.prototype.moveAhead = function (step) {
  25082. if (step === void 0) { step = 0.002; }
  25083. this.move(step);
  25084. return this;
  25085. };
  25086. PathCursor.prototype.moveBack = function (step) {
  25087. if (step === void 0) { step = 0.002; }
  25088. this.move(-step);
  25089. return this;
  25090. };
  25091. PathCursor.prototype.move = function (step) {
  25092. if (Math.abs(step) > 1) {
  25093. throw "step size should be less than 1.";
  25094. }
  25095. this.value += step;
  25096. this.ensureLimits();
  25097. this.raiseOnChange();
  25098. return this;
  25099. };
  25100. PathCursor.prototype.ensureLimits = function () {
  25101. while (this.value > 1) {
  25102. this.value -= 1;
  25103. }
  25104. while (this.value < 0) {
  25105. this.value += 1;
  25106. }
  25107. return this;
  25108. };
  25109. // used by animation engine
  25110. PathCursor.prototype.markAsDirty = function (propertyName) {
  25111. this.ensureLimits();
  25112. this.raiseOnChange();
  25113. return this;
  25114. };
  25115. PathCursor.prototype.raiseOnChange = function () {
  25116. var _this = this;
  25117. this._onchange.forEach(function (f) { return f(_this); });
  25118. return this;
  25119. };
  25120. PathCursor.prototype.onchange = function (f) {
  25121. this._onchange.push(f);
  25122. return this;
  25123. };
  25124. return PathCursor;
  25125. })();
  25126. BABYLON.PathCursor = PathCursor;
  25127. var Animation = (function () {
  25128. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25129. this.name = name;
  25130. this.targetProperty = targetProperty;
  25131. this.framePerSecond = framePerSecond;
  25132. this.dataType = dataType;
  25133. this.loopMode = loopMode;
  25134. this.enableBlending = enableBlending;
  25135. this._offsetsCache = {};
  25136. this._highLimitsCache = {};
  25137. this._stopped = false;
  25138. this._blendingFactor = 0;
  25139. // The set of event that will be linked to this animation
  25140. this._events = new Array();
  25141. this.allowMatricesInterpolation = false;
  25142. this.blendingSpeed = 0.01;
  25143. this._ranges = {};
  25144. this.targetPropertyPath = targetProperty.split(".");
  25145. this.dataType = dataType;
  25146. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25147. }
  25148. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25149. var dataType = undefined;
  25150. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25151. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25152. }
  25153. else if (from instanceof BABYLON.Quaternion) {
  25154. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25155. }
  25156. else if (from instanceof BABYLON.Vector3) {
  25157. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25158. }
  25159. else if (from instanceof BABYLON.Vector2) {
  25160. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25161. }
  25162. else if (from instanceof BABYLON.Color3) {
  25163. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25164. }
  25165. if (dataType == undefined) {
  25166. return null;
  25167. }
  25168. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25169. var keys = [];
  25170. keys.push({ frame: 0, value: from });
  25171. keys.push({ frame: totalFrame, value: to });
  25172. animation.setKeys(keys);
  25173. if (easingFunction !== undefined) {
  25174. animation.setEasingFunction(easingFunction);
  25175. }
  25176. return animation;
  25177. };
  25178. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25179. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25180. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25181. };
  25182. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25183. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25184. node.animations.push(animation);
  25185. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25186. };
  25187. // Methods
  25188. /**
  25189. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25190. */
  25191. Animation.prototype.toString = function (fullDetails) {
  25192. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25193. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25194. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25195. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25196. if (fullDetails) {
  25197. ret += ", Ranges: {";
  25198. var first = true;
  25199. for (var name in this._ranges) {
  25200. if (!first) {
  25201. ret + ", ";
  25202. first = false;
  25203. }
  25204. ret += name;
  25205. }
  25206. ret += "}";
  25207. }
  25208. return ret;
  25209. };
  25210. /**
  25211. * Add an event to this animation.
  25212. */
  25213. Animation.prototype.addEvent = function (event) {
  25214. this._events.push(event);
  25215. };
  25216. /**
  25217. * Remove all events found at the given frame
  25218. * @param frame
  25219. */
  25220. Animation.prototype.removeEvents = function (frame) {
  25221. for (var index = 0; index < this._events.length; index++) {
  25222. if (this._events[index].frame === frame) {
  25223. this._events.splice(index, 1);
  25224. index--;
  25225. }
  25226. }
  25227. };
  25228. Animation.prototype.createRange = function (name, from, to) {
  25229. // check name not already in use; could happen for bones after serialized
  25230. if (!this._ranges[name]) {
  25231. this._ranges[name] = new AnimationRange(name, from, to);
  25232. }
  25233. };
  25234. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25235. if (deleteFrames === void 0) { deleteFrames = true; }
  25236. if (this._ranges[name]) {
  25237. if (deleteFrames) {
  25238. var from = this._ranges[name].from;
  25239. var to = this._ranges[name].to;
  25240. // this loop MUST go high to low for multiple splices to work
  25241. for (var key = this._keys.length - 1; key >= 0; key--) {
  25242. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25243. this._keys.splice(key, 1);
  25244. }
  25245. }
  25246. }
  25247. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25248. }
  25249. };
  25250. Animation.prototype.getRange = function (name) {
  25251. return this._ranges[name];
  25252. };
  25253. Animation.prototype.reset = function () {
  25254. this._offsetsCache = {};
  25255. this._highLimitsCache = {};
  25256. this.currentFrame = 0;
  25257. this._blendingFactor = 0;
  25258. this._originalBlendValue = null;
  25259. };
  25260. Animation.prototype.isStopped = function () {
  25261. return this._stopped;
  25262. };
  25263. Animation.prototype.getKeys = function () {
  25264. return this._keys;
  25265. };
  25266. Animation.prototype.getHighestFrame = function () {
  25267. var ret = 0;
  25268. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25269. if (ret < this._keys[key].frame) {
  25270. ret = this._keys[key].frame;
  25271. }
  25272. }
  25273. return ret;
  25274. };
  25275. Animation.prototype.getEasingFunction = function () {
  25276. return this._easingFunction;
  25277. };
  25278. Animation.prototype.setEasingFunction = function (easingFunction) {
  25279. this._easingFunction = easingFunction;
  25280. };
  25281. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25282. return startValue + (endValue - startValue) * gradient;
  25283. };
  25284. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25285. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25286. };
  25287. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25288. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25289. };
  25290. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25291. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25292. };
  25293. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25294. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25295. };
  25296. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25297. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25298. };
  25299. Animation.prototype.clone = function () {
  25300. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25301. if (this._keys) {
  25302. clone.setKeys(this._keys);
  25303. }
  25304. if (this._ranges) {
  25305. clone._ranges = {};
  25306. for (var name in this._ranges) {
  25307. clone._ranges[name] = this._ranges[name].clone();
  25308. }
  25309. }
  25310. return clone;
  25311. };
  25312. Animation.prototype.setKeys = function (values) {
  25313. this._keys = values.slice(0);
  25314. this._offsetsCache = {};
  25315. this._highLimitsCache = {};
  25316. };
  25317. Animation.prototype._getKeyValue = function (value) {
  25318. if (typeof value === "function") {
  25319. return value();
  25320. }
  25321. return value;
  25322. };
  25323. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25324. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25325. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25326. }
  25327. this.currentFrame = currentFrame;
  25328. // Try to get a hash to find the right key
  25329. 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));
  25330. if (this._keys[startKey].frame >= currentFrame) {
  25331. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25332. startKey--;
  25333. }
  25334. }
  25335. for (var key = startKey; key < this._keys.length; key++) {
  25336. if (this._keys[key + 1].frame >= currentFrame) {
  25337. var startValue = this._getKeyValue(this._keys[key].value);
  25338. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25339. // gradient : percent of currentFrame between the frame inf and the frame sup
  25340. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25341. // check for easingFunction and correction of gradient
  25342. if (this._easingFunction != null) {
  25343. gradient = this._easingFunction.ease(gradient);
  25344. }
  25345. switch (this.dataType) {
  25346. // Float
  25347. case Animation.ANIMATIONTYPE_FLOAT:
  25348. switch (loopMode) {
  25349. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25350. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25351. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25352. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25353. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25354. }
  25355. break;
  25356. // Quaternion
  25357. case Animation.ANIMATIONTYPE_QUATERNION:
  25358. var quaternion = null;
  25359. switch (loopMode) {
  25360. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25361. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25362. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25363. break;
  25364. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25365. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25366. break;
  25367. }
  25368. return quaternion;
  25369. // Vector3
  25370. case Animation.ANIMATIONTYPE_VECTOR3:
  25371. switch (loopMode) {
  25372. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25373. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25374. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25375. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25376. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25377. }
  25378. // Vector2
  25379. case Animation.ANIMATIONTYPE_VECTOR2:
  25380. switch (loopMode) {
  25381. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25382. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25383. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25384. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25385. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25386. }
  25387. // Color3
  25388. case Animation.ANIMATIONTYPE_COLOR3:
  25389. switch (loopMode) {
  25390. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25391. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25392. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25393. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25394. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25395. }
  25396. // Matrix
  25397. case Animation.ANIMATIONTYPE_MATRIX:
  25398. switch (loopMode) {
  25399. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25400. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25401. if (this.allowMatricesInterpolation) {
  25402. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25403. }
  25404. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25405. return startValue;
  25406. }
  25407. default:
  25408. break;
  25409. }
  25410. break;
  25411. }
  25412. }
  25413. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25414. };
  25415. Animation.prototype.setValue = function (currentValue, blend) {
  25416. if (blend === void 0) { blend = false; }
  25417. // Set value
  25418. var path;
  25419. var destination;
  25420. if (this.targetPropertyPath.length > 1) {
  25421. var property = this._target[this.targetPropertyPath[0]];
  25422. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25423. property = property[this.targetPropertyPath[index]];
  25424. }
  25425. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25426. destination = property;
  25427. }
  25428. else {
  25429. path = this.targetPropertyPath[0];
  25430. destination = this._target;
  25431. }
  25432. // Blending
  25433. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25434. if (!this._originalBlendValue) {
  25435. this._originalBlendValue = destination[path];
  25436. }
  25437. if (this._originalBlendValue.prototype) {
  25438. if (this._originalBlendValue.prototype.Lerp) {
  25439. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25440. }
  25441. else {
  25442. destination[path] = currentValue;
  25443. }
  25444. }
  25445. else {
  25446. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25447. }
  25448. this._blendingFactor += this.blendingSpeed;
  25449. }
  25450. else {
  25451. destination[path] = currentValue;
  25452. }
  25453. if (this._target.markAsDirty) {
  25454. this._target.markAsDirty(this.targetProperty);
  25455. }
  25456. };
  25457. Animation.prototype.goToFrame = function (frame) {
  25458. if (frame < this._keys[0].frame) {
  25459. frame = this._keys[0].frame;
  25460. }
  25461. else if (frame > this._keys[this._keys.length - 1].frame) {
  25462. frame = this._keys[this._keys.length - 1].frame;
  25463. }
  25464. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25465. this.setValue(currentValue);
  25466. };
  25467. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25468. if (blend === void 0) { blend = false; }
  25469. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25470. this._stopped = true;
  25471. return false;
  25472. }
  25473. var returnValue = true;
  25474. // Adding a start key at frame 0 if missing
  25475. if (this._keys[0].frame !== 0) {
  25476. var newKey = { frame: 0, value: this._keys[0].value };
  25477. this._keys.splice(0, 0, newKey);
  25478. }
  25479. // Check limits
  25480. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25481. from = this._keys[0].frame;
  25482. }
  25483. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25484. to = this._keys[this._keys.length - 1].frame;
  25485. }
  25486. // Compute ratio
  25487. var range = to - from;
  25488. var offsetValue;
  25489. // ratio represents the frame delta between from and to
  25490. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25491. var highLimitValue = 0;
  25492. if (ratio > range && !loop) {
  25493. returnValue = false;
  25494. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25495. }
  25496. else {
  25497. // Get max value if required
  25498. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25499. var keyOffset = to.toString() + from.toString();
  25500. if (!this._offsetsCache[keyOffset]) {
  25501. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25502. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25503. switch (this.dataType) {
  25504. // Float
  25505. case Animation.ANIMATIONTYPE_FLOAT:
  25506. this._offsetsCache[keyOffset] = toValue - fromValue;
  25507. break;
  25508. // Quaternion
  25509. case Animation.ANIMATIONTYPE_QUATERNION:
  25510. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25511. break;
  25512. // Vector3
  25513. case Animation.ANIMATIONTYPE_VECTOR3:
  25514. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25515. // Vector2
  25516. case Animation.ANIMATIONTYPE_VECTOR2:
  25517. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25518. // Color3
  25519. case Animation.ANIMATIONTYPE_COLOR3:
  25520. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25521. default:
  25522. break;
  25523. }
  25524. this._highLimitsCache[keyOffset] = toValue;
  25525. }
  25526. highLimitValue = this._highLimitsCache[keyOffset];
  25527. offsetValue = this._offsetsCache[keyOffset];
  25528. }
  25529. }
  25530. if (offsetValue === undefined) {
  25531. switch (this.dataType) {
  25532. // Float
  25533. case Animation.ANIMATIONTYPE_FLOAT:
  25534. offsetValue = 0;
  25535. break;
  25536. // Quaternion
  25537. case Animation.ANIMATIONTYPE_QUATERNION:
  25538. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25539. break;
  25540. // Vector3
  25541. case Animation.ANIMATIONTYPE_VECTOR3:
  25542. offsetValue = BABYLON.Vector3.Zero();
  25543. break;
  25544. // Vector2
  25545. case Animation.ANIMATIONTYPE_VECTOR2:
  25546. offsetValue = BABYLON.Vector2.Zero();
  25547. break;
  25548. // Color3
  25549. case Animation.ANIMATIONTYPE_COLOR3:
  25550. offsetValue = BABYLON.Color3.Black();
  25551. }
  25552. }
  25553. // Compute value
  25554. var repeatCount = (ratio / range) >> 0;
  25555. var currentFrame = returnValue ? from + ratio % range : to;
  25556. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25557. // Set value
  25558. this.setValue(currentValue);
  25559. // Check events
  25560. for (var index = 0; index < this._events.length; index++) {
  25561. if (currentFrame >= this._events[index].frame) {
  25562. var event = this._events[index];
  25563. if (!event.isDone) {
  25564. // If event should be done only once, remove it.
  25565. if (event.onlyOnce) {
  25566. this._events.splice(index, 1);
  25567. index--;
  25568. }
  25569. event.isDone = true;
  25570. event.action();
  25571. } // Don't do anything if the event has already be done.
  25572. }
  25573. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25574. // reset event, the animation is looping
  25575. this._events[index].isDone = false;
  25576. }
  25577. }
  25578. if (!returnValue) {
  25579. this._stopped = true;
  25580. }
  25581. return returnValue;
  25582. };
  25583. Animation.prototype.serialize = function () {
  25584. var serializationObject = {};
  25585. serializationObject.name = this.name;
  25586. serializationObject.property = this.targetProperty;
  25587. serializationObject.framePerSecond = this.framePerSecond;
  25588. serializationObject.dataType = this.dataType;
  25589. serializationObject.loopBehavior = this.loopMode;
  25590. var dataType = this.dataType;
  25591. serializationObject.keys = [];
  25592. var keys = this.getKeys();
  25593. for (var index = 0; index < keys.length; index++) {
  25594. var animationKey = keys[index];
  25595. var key = {};
  25596. key.frame = animationKey.frame;
  25597. switch (dataType) {
  25598. case Animation.ANIMATIONTYPE_FLOAT:
  25599. key.values = [animationKey.value];
  25600. break;
  25601. case Animation.ANIMATIONTYPE_QUATERNION:
  25602. case Animation.ANIMATIONTYPE_MATRIX:
  25603. case Animation.ANIMATIONTYPE_VECTOR3:
  25604. case Animation.ANIMATIONTYPE_COLOR3:
  25605. key.values = animationKey.value.asArray();
  25606. break;
  25607. }
  25608. serializationObject.keys.push(key);
  25609. }
  25610. serializationObject.ranges = [];
  25611. for (var name in this._ranges) {
  25612. var range = {};
  25613. range.name = name;
  25614. range.from = this._ranges[name].from;
  25615. range.to = this._ranges[name].to;
  25616. serializationObject.ranges.push(range);
  25617. }
  25618. return serializationObject;
  25619. };
  25620. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25621. get: function () {
  25622. return Animation._ANIMATIONTYPE_FLOAT;
  25623. },
  25624. enumerable: true,
  25625. configurable: true
  25626. });
  25627. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25628. get: function () {
  25629. return Animation._ANIMATIONTYPE_VECTOR3;
  25630. },
  25631. enumerable: true,
  25632. configurable: true
  25633. });
  25634. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25635. get: function () {
  25636. return Animation._ANIMATIONTYPE_VECTOR2;
  25637. },
  25638. enumerable: true,
  25639. configurable: true
  25640. });
  25641. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25642. get: function () {
  25643. return Animation._ANIMATIONTYPE_QUATERNION;
  25644. },
  25645. enumerable: true,
  25646. configurable: true
  25647. });
  25648. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25649. get: function () {
  25650. return Animation._ANIMATIONTYPE_MATRIX;
  25651. },
  25652. enumerable: true,
  25653. configurable: true
  25654. });
  25655. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25656. get: function () {
  25657. return Animation._ANIMATIONTYPE_COLOR3;
  25658. },
  25659. enumerable: true,
  25660. configurable: true
  25661. });
  25662. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25663. get: function () {
  25664. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25665. },
  25666. enumerable: true,
  25667. configurable: true
  25668. });
  25669. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25670. get: function () {
  25671. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25672. },
  25673. enumerable: true,
  25674. configurable: true
  25675. });
  25676. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25677. get: function () {
  25678. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25679. },
  25680. enumerable: true,
  25681. configurable: true
  25682. });
  25683. Animation.Parse = function (parsedAnimation) {
  25684. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25685. var dataType = parsedAnimation.dataType;
  25686. var keys = [];
  25687. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25688. var key = parsedAnimation.keys[index];
  25689. var data;
  25690. switch (dataType) {
  25691. case Animation.ANIMATIONTYPE_FLOAT:
  25692. data = key.values[0];
  25693. break;
  25694. case Animation.ANIMATIONTYPE_QUATERNION:
  25695. data = BABYLON.Quaternion.FromArray(key.values);
  25696. break;
  25697. case Animation.ANIMATIONTYPE_MATRIX:
  25698. data = BABYLON.Matrix.FromArray(key.values);
  25699. break;
  25700. case Animation.ANIMATIONTYPE_COLOR3:
  25701. data = BABYLON.Color3.FromArray(key.values);
  25702. break;
  25703. case Animation.ANIMATIONTYPE_VECTOR3:
  25704. default:
  25705. data = BABYLON.Vector3.FromArray(key.values);
  25706. break;
  25707. }
  25708. keys.push({
  25709. frame: key.frame,
  25710. value: data
  25711. });
  25712. }
  25713. animation.setKeys(keys);
  25714. if (parsedAnimation.ranges) {
  25715. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25716. data = parsedAnimation.ranges[index];
  25717. animation.createRange(data.name, data.from, data.to);
  25718. }
  25719. }
  25720. return animation;
  25721. };
  25722. Animation.AppendSerializedAnimations = function (source, destination) {
  25723. if (source.animations) {
  25724. destination.animations = [];
  25725. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25726. var animation = source.animations[animationIndex];
  25727. destination.animations.push(animation.serialize());
  25728. }
  25729. }
  25730. };
  25731. // Statics
  25732. Animation._ANIMATIONTYPE_FLOAT = 0;
  25733. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25734. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25735. Animation._ANIMATIONTYPE_MATRIX = 3;
  25736. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25737. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25738. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25739. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25740. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25741. return Animation;
  25742. })();
  25743. BABYLON.Animation = Animation;
  25744. })(BABYLON || (BABYLON = {}));
  25745. var BABYLON;
  25746. (function (BABYLON) {
  25747. var Animatable = (function () {
  25748. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25749. if (fromFrame === void 0) { fromFrame = 0; }
  25750. if (toFrame === void 0) { toFrame = 100; }
  25751. if (loopAnimation === void 0) { loopAnimation = false; }
  25752. if (speedRatio === void 0) { speedRatio = 1.0; }
  25753. this.target = target;
  25754. this.fromFrame = fromFrame;
  25755. this.toFrame = toFrame;
  25756. this.loopAnimation = loopAnimation;
  25757. this.speedRatio = speedRatio;
  25758. this.onAnimationEnd = onAnimationEnd;
  25759. this._animations = new Array();
  25760. this._paused = false;
  25761. this.animationStarted = false;
  25762. if (animations) {
  25763. this.appendAnimations(target, animations);
  25764. }
  25765. this._scene = scene;
  25766. scene._activeAnimatables.push(this);
  25767. }
  25768. // Methods
  25769. Animatable.prototype.getAnimations = function () {
  25770. return this._animations;
  25771. };
  25772. Animatable.prototype.appendAnimations = function (target, animations) {
  25773. for (var index = 0; index < animations.length; index++) {
  25774. var animation = animations[index];
  25775. animation._target = target;
  25776. this._animations.push(animation);
  25777. }
  25778. };
  25779. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25780. var animations = this._animations;
  25781. for (var index = 0; index < animations.length; index++) {
  25782. if (animations[index].targetProperty === property) {
  25783. return animations[index];
  25784. }
  25785. }
  25786. return null;
  25787. };
  25788. Animatable.prototype.reset = function () {
  25789. var animations = this._animations;
  25790. for (var index = 0; index < animations.length; index++) {
  25791. animations[index].reset();
  25792. }
  25793. this._localDelayOffset = null;
  25794. this._pausedDelay = null;
  25795. };
  25796. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25797. var animations = this._animations;
  25798. for (var index = 0; index < animations.length; index++) {
  25799. animations[index].enableBlending = true;
  25800. animations[index].blendingSpeed = blendingSpeed;
  25801. }
  25802. };
  25803. Animatable.prototype.disableBlending = function () {
  25804. var animations = this._animations;
  25805. for (var index = 0; index < animations.length; index++) {
  25806. animations[index].enableBlending = false;
  25807. }
  25808. };
  25809. Animatable.prototype.goToFrame = function (frame) {
  25810. var animations = this._animations;
  25811. for (var index = 0; index < animations.length; index++) {
  25812. animations[index].goToFrame(frame);
  25813. }
  25814. };
  25815. Animatable.prototype.pause = function () {
  25816. if (this._paused) {
  25817. return;
  25818. }
  25819. this._paused = true;
  25820. };
  25821. Animatable.prototype.restart = function () {
  25822. this._paused = false;
  25823. };
  25824. Animatable.prototype.stop = function () {
  25825. var index = this._scene._activeAnimatables.indexOf(this);
  25826. if (index > -1) {
  25827. this._scene._activeAnimatables.splice(index, 1);
  25828. var animations = this._animations;
  25829. for (var index = 0; index < animations.length; index++) {
  25830. animations[index].reset();
  25831. }
  25832. if (this.onAnimationEnd) {
  25833. this.onAnimationEnd();
  25834. }
  25835. }
  25836. };
  25837. Animatable.prototype._animate = function (delay) {
  25838. if (this._paused) {
  25839. this.animationStarted = false;
  25840. if (!this._pausedDelay) {
  25841. this._pausedDelay = delay;
  25842. }
  25843. return true;
  25844. }
  25845. if (!this._localDelayOffset) {
  25846. this._localDelayOffset = delay;
  25847. }
  25848. else if (this._pausedDelay) {
  25849. this._localDelayOffset += delay - this._pausedDelay;
  25850. this._pausedDelay = null;
  25851. }
  25852. // Animating
  25853. var running = false;
  25854. var animations = this._animations;
  25855. var index;
  25856. for (index = 0; index < animations.length; index++) {
  25857. var animation = animations[index];
  25858. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  25859. running = running || isRunning;
  25860. }
  25861. this.animationStarted = running;
  25862. if (!running) {
  25863. // Remove from active animatables
  25864. index = this._scene._activeAnimatables.indexOf(this);
  25865. this._scene._activeAnimatables.splice(index, 1);
  25866. }
  25867. if (!running && this.onAnimationEnd) {
  25868. this.onAnimationEnd();
  25869. this.onAnimationEnd = null;
  25870. }
  25871. return running;
  25872. };
  25873. return Animatable;
  25874. })();
  25875. BABYLON.Animatable = Animatable;
  25876. })(BABYLON || (BABYLON = {}));
  25877. var BABYLON;
  25878. (function (BABYLON) {
  25879. var EasingFunction = (function () {
  25880. function EasingFunction() {
  25881. // Properties
  25882. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  25883. }
  25884. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  25885. get: function () {
  25886. return EasingFunction._EASINGMODE_EASEIN;
  25887. },
  25888. enumerable: true,
  25889. configurable: true
  25890. });
  25891. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  25892. get: function () {
  25893. return EasingFunction._EASINGMODE_EASEOUT;
  25894. },
  25895. enumerable: true,
  25896. configurable: true
  25897. });
  25898. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  25899. get: function () {
  25900. return EasingFunction._EASINGMODE_EASEINOUT;
  25901. },
  25902. enumerable: true,
  25903. configurable: true
  25904. });
  25905. EasingFunction.prototype.setEasingMode = function (easingMode) {
  25906. var n = Math.min(Math.max(easingMode, 0), 2);
  25907. this._easingMode = n;
  25908. };
  25909. EasingFunction.prototype.getEasingMode = function () {
  25910. return this._easingMode;
  25911. };
  25912. EasingFunction.prototype.easeInCore = function (gradient) {
  25913. throw new Error('You must implement this method');
  25914. };
  25915. EasingFunction.prototype.ease = function (gradient) {
  25916. switch (this._easingMode) {
  25917. case EasingFunction.EASINGMODE_EASEIN:
  25918. return this.easeInCore(gradient);
  25919. case EasingFunction.EASINGMODE_EASEOUT:
  25920. return (1 - this.easeInCore(1 - gradient));
  25921. }
  25922. if (gradient >= 0.5) {
  25923. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  25924. }
  25925. return (this.easeInCore(gradient * 2) * 0.5);
  25926. };
  25927. //Statics
  25928. EasingFunction._EASINGMODE_EASEIN = 0;
  25929. EasingFunction._EASINGMODE_EASEOUT = 1;
  25930. EasingFunction._EASINGMODE_EASEINOUT = 2;
  25931. return EasingFunction;
  25932. })();
  25933. BABYLON.EasingFunction = EasingFunction;
  25934. var CircleEase = (function (_super) {
  25935. __extends(CircleEase, _super);
  25936. function CircleEase() {
  25937. _super.apply(this, arguments);
  25938. }
  25939. CircleEase.prototype.easeInCore = function (gradient) {
  25940. gradient = Math.max(0, Math.min(1, gradient));
  25941. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  25942. };
  25943. return CircleEase;
  25944. })(EasingFunction);
  25945. BABYLON.CircleEase = CircleEase;
  25946. var BackEase = (function (_super) {
  25947. __extends(BackEase, _super);
  25948. function BackEase(amplitude) {
  25949. if (amplitude === void 0) { amplitude = 1; }
  25950. _super.call(this);
  25951. this.amplitude = amplitude;
  25952. }
  25953. BackEase.prototype.easeInCore = function (gradient) {
  25954. var num = Math.max(0, this.amplitude);
  25955. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  25956. };
  25957. return BackEase;
  25958. })(EasingFunction);
  25959. BABYLON.BackEase = BackEase;
  25960. var BounceEase = (function (_super) {
  25961. __extends(BounceEase, _super);
  25962. function BounceEase(bounces, bounciness) {
  25963. if (bounces === void 0) { bounces = 3; }
  25964. if (bounciness === void 0) { bounciness = 2; }
  25965. _super.call(this);
  25966. this.bounces = bounces;
  25967. this.bounciness = bounciness;
  25968. }
  25969. BounceEase.prototype.easeInCore = function (gradient) {
  25970. var y = Math.max(0.0, this.bounces);
  25971. var bounciness = this.bounciness;
  25972. if (bounciness <= 1.0) {
  25973. bounciness = 1.001;
  25974. }
  25975. var num9 = Math.pow(bounciness, y);
  25976. var num5 = 1.0 - bounciness;
  25977. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  25978. var num15 = gradient * num4;
  25979. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  25980. var num3 = Math.floor(num65);
  25981. var num13 = num3 + 1.0;
  25982. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  25983. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  25984. var num7 = (num8 + num12) * 0.5;
  25985. var num6 = gradient - num7;
  25986. var num2 = num7 - num8;
  25987. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  25988. };
  25989. return BounceEase;
  25990. })(EasingFunction);
  25991. BABYLON.BounceEase = BounceEase;
  25992. var CubicEase = (function (_super) {
  25993. __extends(CubicEase, _super);
  25994. function CubicEase() {
  25995. _super.apply(this, arguments);
  25996. }
  25997. CubicEase.prototype.easeInCore = function (gradient) {
  25998. return (gradient * gradient * gradient);
  25999. };
  26000. return CubicEase;
  26001. })(EasingFunction);
  26002. BABYLON.CubicEase = CubicEase;
  26003. var ElasticEase = (function (_super) {
  26004. __extends(ElasticEase, _super);
  26005. function ElasticEase(oscillations, springiness) {
  26006. if (oscillations === void 0) { oscillations = 3; }
  26007. if (springiness === void 0) { springiness = 3; }
  26008. _super.call(this);
  26009. this.oscillations = oscillations;
  26010. this.springiness = springiness;
  26011. }
  26012. ElasticEase.prototype.easeInCore = function (gradient) {
  26013. var num2;
  26014. var num3 = Math.max(0.0, this.oscillations);
  26015. var num = Math.max(0.0, this.springiness);
  26016. if (num == 0) {
  26017. num2 = gradient;
  26018. }
  26019. else {
  26020. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  26021. }
  26022. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  26023. };
  26024. return ElasticEase;
  26025. })(EasingFunction);
  26026. BABYLON.ElasticEase = ElasticEase;
  26027. var ExponentialEase = (function (_super) {
  26028. __extends(ExponentialEase, _super);
  26029. function ExponentialEase(exponent) {
  26030. if (exponent === void 0) { exponent = 2; }
  26031. _super.call(this);
  26032. this.exponent = exponent;
  26033. }
  26034. ExponentialEase.prototype.easeInCore = function (gradient) {
  26035. if (this.exponent <= 0) {
  26036. return gradient;
  26037. }
  26038. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  26039. };
  26040. return ExponentialEase;
  26041. })(EasingFunction);
  26042. BABYLON.ExponentialEase = ExponentialEase;
  26043. var PowerEase = (function (_super) {
  26044. __extends(PowerEase, _super);
  26045. function PowerEase(power) {
  26046. if (power === void 0) { power = 2; }
  26047. _super.call(this);
  26048. this.power = power;
  26049. }
  26050. PowerEase.prototype.easeInCore = function (gradient) {
  26051. var y = Math.max(0.0, this.power);
  26052. return Math.pow(gradient, y);
  26053. };
  26054. return PowerEase;
  26055. })(EasingFunction);
  26056. BABYLON.PowerEase = PowerEase;
  26057. var QuadraticEase = (function (_super) {
  26058. __extends(QuadraticEase, _super);
  26059. function QuadraticEase() {
  26060. _super.apply(this, arguments);
  26061. }
  26062. QuadraticEase.prototype.easeInCore = function (gradient) {
  26063. return (gradient * gradient);
  26064. };
  26065. return QuadraticEase;
  26066. })(EasingFunction);
  26067. BABYLON.QuadraticEase = QuadraticEase;
  26068. var QuarticEase = (function (_super) {
  26069. __extends(QuarticEase, _super);
  26070. function QuarticEase() {
  26071. _super.apply(this, arguments);
  26072. }
  26073. QuarticEase.prototype.easeInCore = function (gradient) {
  26074. return (gradient * gradient * gradient * gradient);
  26075. };
  26076. return QuarticEase;
  26077. })(EasingFunction);
  26078. BABYLON.QuarticEase = QuarticEase;
  26079. var QuinticEase = (function (_super) {
  26080. __extends(QuinticEase, _super);
  26081. function QuinticEase() {
  26082. _super.apply(this, arguments);
  26083. }
  26084. QuinticEase.prototype.easeInCore = function (gradient) {
  26085. return (gradient * gradient * gradient * gradient * gradient);
  26086. };
  26087. return QuinticEase;
  26088. })(EasingFunction);
  26089. BABYLON.QuinticEase = QuinticEase;
  26090. var SineEase = (function (_super) {
  26091. __extends(SineEase, _super);
  26092. function SineEase() {
  26093. _super.apply(this, arguments);
  26094. }
  26095. SineEase.prototype.easeInCore = function (gradient) {
  26096. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26097. };
  26098. return SineEase;
  26099. })(EasingFunction);
  26100. BABYLON.SineEase = SineEase;
  26101. var BezierCurveEase = (function (_super) {
  26102. __extends(BezierCurveEase, _super);
  26103. function BezierCurveEase(x1, y1, x2, y2) {
  26104. if (x1 === void 0) { x1 = 0; }
  26105. if (y1 === void 0) { y1 = 0; }
  26106. if (x2 === void 0) { x2 = 1; }
  26107. if (y2 === void 0) { y2 = 1; }
  26108. _super.call(this);
  26109. this.x1 = x1;
  26110. this.y1 = y1;
  26111. this.x2 = x2;
  26112. this.y2 = y2;
  26113. }
  26114. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26115. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26116. };
  26117. return BezierCurveEase;
  26118. })(EasingFunction);
  26119. BABYLON.BezierCurveEase = BezierCurveEase;
  26120. })(BABYLON || (BABYLON = {}));
  26121. var BABYLON;
  26122. (function (BABYLON) {
  26123. var Bone = (function (_super) {
  26124. __extends(Bone, _super);
  26125. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26126. _super.call(this, name, skeleton.getScene());
  26127. this.name = name;
  26128. this.children = new Array();
  26129. this.animations = new Array();
  26130. this._worldTransform = new BABYLON.Matrix();
  26131. this._absoluteTransform = new BABYLON.Matrix();
  26132. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26133. this._skeleton = skeleton;
  26134. this._matrix = matrix;
  26135. this._baseMatrix = matrix;
  26136. this._restPose = restPose ? restPose : matrix.clone();
  26137. skeleton.bones.push(this);
  26138. if (parentBone) {
  26139. this._parent = parentBone;
  26140. parentBone.children.push(this);
  26141. }
  26142. else {
  26143. this._parent = null;
  26144. }
  26145. this._updateDifferenceMatrix();
  26146. }
  26147. // Members
  26148. Bone.prototype.getParent = function () {
  26149. return this._parent;
  26150. };
  26151. Bone.prototype.getLocalMatrix = function () {
  26152. return this._matrix;
  26153. };
  26154. Bone.prototype.getBaseMatrix = function () {
  26155. return this._baseMatrix;
  26156. };
  26157. Bone.prototype.getRestPose = function () {
  26158. return this._restPose;
  26159. };
  26160. Bone.prototype.returnToRest = function () {
  26161. this.updateMatrix(this._restPose.clone());
  26162. };
  26163. Bone.prototype.getWorldMatrix = function () {
  26164. return this._worldTransform;
  26165. };
  26166. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26167. return this._invertedAbsoluteTransform;
  26168. };
  26169. Bone.prototype.getAbsoluteTransform = function () {
  26170. return this._absoluteTransform;
  26171. };
  26172. // Methods
  26173. Bone.prototype.updateMatrix = function (matrix) {
  26174. this._baseMatrix = matrix.clone();
  26175. this._matrix = matrix.clone();
  26176. this._skeleton._markAsDirty();
  26177. this._updateDifferenceMatrix();
  26178. };
  26179. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26180. if (!rootMatrix) {
  26181. rootMatrix = this._baseMatrix;
  26182. }
  26183. if (this._parent) {
  26184. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26185. }
  26186. else {
  26187. this._absoluteTransform.copyFrom(rootMatrix);
  26188. }
  26189. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26190. for (var index = 0; index < this.children.length; index++) {
  26191. this.children[index]._updateDifferenceMatrix();
  26192. }
  26193. };
  26194. Bone.prototype.markAsDirty = function () {
  26195. this._currentRenderId++;
  26196. this._skeleton._markAsDirty();
  26197. };
  26198. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26199. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26200. // all animation may be coming from a library skeleton, so may need to create animation
  26201. if (this.animations.length === 0) {
  26202. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26203. this.animations[0].setKeys([]);
  26204. }
  26205. // get animation info / verify there is such a range from the source bone
  26206. var sourceRange = source.animations[0].getRange(rangeName);
  26207. if (!sourceRange) {
  26208. return false;
  26209. }
  26210. var from = sourceRange.from;
  26211. var to = sourceRange.to;
  26212. var sourceKeys = source.animations[0].getKeys();
  26213. // rescaling prep
  26214. var sourceBoneLength = source.length;
  26215. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26216. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26217. var destKeys = this.animations[0].getKeys();
  26218. // loop vars declaration / initialization
  26219. var orig;
  26220. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26221. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26222. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26223. var mat;
  26224. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26225. orig = sourceKeys[key];
  26226. if (orig.frame >= from && orig.frame <= to) {
  26227. if (scalingReqd) {
  26228. orig.value.decompose(origScale, origRotation, origTranslation);
  26229. origTranslation.scaleInPlace(ratio);
  26230. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26231. }
  26232. else {
  26233. mat = orig.value;
  26234. }
  26235. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26236. }
  26237. }
  26238. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26239. return true;
  26240. };
  26241. return Bone;
  26242. })(BABYLON.Node);
  26243. BABYLON.Bone = Bone;
  26244. })(BABYLON || (BABYLON = {}));
  26245. var BABYLON;
  26246. (function (BABYLON) {
  26247. var Skeleton = (function () {
  26248. function Skeleton(name, id, scene) {
  26249. this.name = name;
  26250. this.id = id;
  26251. this.bones = new Array();
  26252. this.needInitialSkinMatrix = false;
  26253. this._isDirty = true;
  26254. this._meshesWithPoseMatrix = new Array();
  26255. this._identity = BABYLON.Matrix.Identity();
  26256. this._ranges = {};
  26257. this.bones = [];
  26258. this._scene = scene;
  26259. scene.skeletons.push(this);
  26260. //make sure it will recalculate the matrix next time prepare is called.
  26261. this._isDirty = true;
  26262. }
  26263. // Members
  26264. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26265. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26266. return mesh._bonesTransformMatrices;
  26267. }
  26268. return this._transformMatrices;
  26269. };
  26270. Skeleton.prototype.getScene = function () {
  26271. return this._scene;
  26272. };
  26273. // Methods
  26274. /**
  26275. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26276. */
  26277. Skeleton.prototype.toString = function (fullDetails) {
  26278. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26279. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26280. if (fullDetails) {
  26281. ret += ", Ranges: {";
  26282. var first = true;
  26283. for (var name in this._ranges) {
  26284. if (!first) {
  26285. ret + ", ";
  26286. first = false;
  26287. }
  26288. ret += name;
  26289. }
  26290. ret += "}";
  26291. }
  26292. return ret;
  26293. };
  26294. /**
  26295. * Get bone's index searching by name
  26296. * @param {string} name is bone's name to search for
  26297. * @return {number} Indice of the bone. Returns -1 if not found
  26298. */
  26299. Skeleton.prototype.getBoneIndexByName = function (name) {
  26300. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26301. if (this.bones[boneIndex].name === name) {
  26302. return boneIndex;
  26303. }
  26304. }
  26305. return -1;
  26306. };
  26307. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26308. // check name not already in use
  26309. if (!this._ranges[name]) {
  26310. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26311. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26312. if (this.bones[i].animations[0]) {
  26313. this.bones[i].animations[0].createRange(name, from, to);
  26314. }
  26315. }
  26316. }
  26317. };
  26318. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26319. if (deleteFrames === void 0) { deleteFrames = true; }
  26320. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26321. if (this.bones[i].animations[0]) {
  26322. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26323. }
  26324. }
  26325. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26326. };
  26327. Skeleton.prototype.getAnimationRange = function (name) {
  26328. return this._ranges[name];
  26329. };
  26330. /**
  26331. * Returns as an Array, all AnimationRanges defined on this skeleton
  26332. */
  26333. Skeleton.prototype.getAnimationRanges = function () {
  26334. var animationRanges = [];
  26335. var name;
  26336. var i = 0;
  26337. for (name in this._ranges) {
  26338. animationRanges[i] = this._ranges[name];
  26339. i++;
  26340. }
  26341. return animationRanges;
  26342. };
  26343. /**
  26344. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26345. */
  26346. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26347. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26348. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26349. return false;
  26350. }
  26351. var ret = true;
  26352. var frameOffset = this._getHighestAnimationFrame() + 1;
  26353. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26354. var boneDict = {};
  26355. var sourceBones = source.bones;
  26356. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26357. boneDict[sourceBones[i].name] = sourceBones[i];
  26358. }
  26359. if (this.bones.length !== sourceBones.length) {
  26360. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26361. ret = false;
  26362. }
  26363. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26364. var boneName = this.bones[i].name;
  26365. var sourceBone = boneDict[boneName];
  26366. if (sourceBone) {
  26367. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26368. }
  26369. else {
  26370. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26371. ret = false;
  26372. }
  26373. }
  26374. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26375. var range = source.getAnimationRange(name);
  26376. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26377. return ret;
  26378. };
  26379. Skeleton.prototype.returnToRest = function () {
  26380. for (var index = 0; index < this.bones.length; index++) {
  26381. this.bones[index].returnToRest();
  26382. }
  26383. };
  26384. Skeleton.prototype._getHighestAnimationFrame = function () {
  26385. var ret = 0;
  26386. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26387. if (this.bones[i].animations[0]) {
  26388. var highest = this.bones[i].animations[0].getHighestFrame();
  26389. if (ret < highest) {
  26390. ret = highest;
  26391. }
  26392. }
  26393. }
  26394. return ret;
  26395. };
  26396. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26397. var range = this.getAnimationRange(name);
  26398. if (!range) {
  26399. return null;
  26400. }
  26401. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26402. };
  26403. Skeleton.prototype._markAsDirty = function () {
  26404. this._isDirty = true;
  26405. };
  26406. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26407. this._meshesWithPoseMatrix.push(mesh);
  26408. };
  26409. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26410. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26411. if (index > -1) {
  26412. this._meshesWithPoseMatrix.splice(index, 1);
  26413. }
  26414. };
  26415. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26416. for (var index = 0; index < this.bones.length; index++) {
  26417. var bone = this.bones[index];
  26418. var parentBone = bone.getParent();
  26419. if (parentBone) {
  26420. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26421. }
  26422. else {
  26423. if (initialSkinMatrix) {
  26424. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26425. }
  26426. else {
  26427. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26428. }
  26429. }
  26430. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26431. }
  26432. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26433. };
  26434. Skeleton.prototype.prepare = function () {
  26435. if (!this._isDirty) {
  26436. return;
  26437. }
  26438. if (this.needInitialSkinMatrix) {
  26439. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26440. var mesh = this._meshesWithPoseMatrix[index];
  26441. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26442. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26443. }
  26444. var poseMatrix = mesh.getPoseMatrix();
  26445. // Prepare bones
  26446. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26447. var bone = this.bones[boneIndex];
  26448. if (!bone.getParent()) {
  26449. var matrix = bone.getBaseMatrix();
  26450. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26451. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26452. }
  26453. }
  26454. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26455. }
  26456. }
  26457. else {
  26458. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26459. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26460. }
  26461. this._computeTransformMatrices(this._transformMatrices, null);
  26462. }
  26463. this._isDirty = false;
  26464. this._scene._activeBones += this.bones.length;
  26465. };
  26466. Skeleton.prototype.getAnimatables = function () {
  26467. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26468. this._animatables = [];
  26469. for (var index = 0; index < this.bones.length; index++) {
  26470. this._animatables.push(this.bones[index]);
  26471. }
  26472. }
  26473. return this._animatables;
  26474. };
  26475. Skeleton.prototype.clone = function (name, id) {
  26476. var result = new Skeleton(name, id || name, this._scene);
  26477. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26478. for (var index = 0; index < this.bones.length; index++) {
  26479. var source = this.bones[index];
  26480. var parentBone = null;
  26481. if (source.getParent()) {
  26482. var parentIndex = this.bones.indexOf(source.getParent());
  26483. parentBone = result.bones[parentIndex];
  26484. }
  26485. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26486. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26487. }
  26488. if (this._ranges) {
  26489. result._ranges = {};
  26490. for (var rangeName in this._ranges) {
  26491. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26492. }
  26493. }
  26494. this._isDirty = true;
  26495. return result;
  26496. };
  26497. Skeleton.prototype.dispose = function () {
  26498. this._meshesWithPoseMatrix = [];
  26499. // Animations
  26500. this.getScene().stopAnimation(this);
  26501. // Remove from scene
  26502. this.getScene().removeSkeleton(this);
  26503. };
  26504. Skeleton.prototype.serialize = function () {
  26505. var serializationObject = {};
  26506. serializationObject.name = this.name;
  26507. serializationObject.id = this.id;
  26508. serializationObject.bones = [];
  26509. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26510. for (var index = 0; index < this.bones.length; index++) {
  26511. var bone = this.bones[index];
  26512. var serializedBone = {
  26513. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26514. name: bone.name,
  26515. matrix: bone.getLocalMatrix().toArray(),
  26516. rest: bone.getRestPose().toArray()
  26517. };
  26518. serializationObject.bones.push(serializedBone);
  26519. if (bone.length) {
  26520. serializedBone.length = bone.length;
  26521. }
  26522. if (bone.animations && bone.animations.length > 0) {
  26523. serializedBone.animation = bone.animations[0].serialize();
  26524. }
  26525. serializationObject.ranges = [];
  26526. for (var name in this._ranges) {
  26527. var range = {};
  26528. range.name = name;
  26529. range.from = this._ranges[name].from;
  26530. range.to = this._ranges[name].to;
  26531. serializationObject.ranges.push(range);
  26532. }
  26533. }
  26534. return serializationObject;
  26535. };
  26536. Skeleton.Parse = function (parsedSkeleton, scene) {
  26537. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26538. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26539. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26540. var parsedBone = parsedSkeleton.bones[index];
  26541. var parentBone = null;
  26542. if (parsedBone.parentBoneIndex > -1) {
  26543. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26544. }
  26545. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26546. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26547. if (parsedBone.length) {
  26548. bone.length = parsedBone.length;
  26549. }
  26550. if (parsedBone.animation) {
  26551. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26552. }
  26553. }
  26554. // placed after bones, so createAnimationRange can cascade down
  26555. if (parsedSkeleton.ranges) {
  26556. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26557. var data = parsedSkeleton.ranges[index];
  26558. skeleton.createAnimationRange(data.name, data.from, data.to);
  26559. }
  26560. }
  26561. return skeleton;
  26562. };
  26563. return Skeleton;
  26564. })();
  26565. BABYLON.Skeleton = Skeleton;
  26566. })(BABYLON || (BABYLON = {}));
  26567. var BABYLON;
  26568. (function (BABYLON) {
  26569. var PostProcess = (function () {
  26570. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26571. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26572. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26573. this.name = name;
  26574. this.width = -1;
  26575. this.height = -1;
  26576. this._reusable = false;
  26577. this._textures = new BABYLON.SmartArray(2);
  26578. this._currentRenderTextureInd = 0;
  26579. if (camera != null) {
  26580. this._camera = camera;
  26581. this._scene = camera.getScene();
  26582. camera.attachPostProcess(this);
  26583. this._engine = this._scene.getEngine();
  26584. }
  26585. else {
  26586. this._engine = engine;
  26587. }
  26588. this._renderRatio = ratio;
  26589. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26590. this._reusable = reusable || false;
  26591. this._textureType = textureType;
  26592. this._samplers = samplers || [];
  26593. this._samplers.push("textureSampler");
  26594. this._fragmentUrl = fragmentUrl;
  26595. this._parameters = parameters || [];
  26596. this.updateEffect(defines);
  26597. }
  26598. PostProcess.prototype.updateEffect = function (defines) {
  26599. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26600. };
  26601. PostProcess.prototype.isReusable = function () {
  26602. return this._reusable;
  26603. };
  26604. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26605. camera = camera || this._camera;
  26606. var scene = camera.getScene();
  26607. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26608. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26609. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26610. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26611. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26612. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26613. if (this._textures.length > 0) {
  26614. for (var i = 0; i < this._textures.length; i++) {
  26615. this._engine._releaseTexture(this._textures.data[i]);
  26616. }
  26617. this._textures.reset();
  26618. }
  26619. this.width = desiredWidth;
  26620. this.height = desiredHeight;
  26621. 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 }));
  26622. if (this._reusable) {
  26623. 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 }));
  26624. }
  26625. if (this.onSizeChanged) {
  26626. this.onSizeChanged();
  26627. }
  26628. }
  26629. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26630. if (this.onActivate) {
  26631. this.onActivate(camera);
  26632. }
  26633. // Clear
  26634. if (this.clearColor) {
  26635. this._engine.clear(this.clearColor, true, true);
  26636. }
  26637. else {
  26638. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26639. }
  26640. if (this._reusable) {
  26641. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26642. }
  26643. };
  26644. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26645. get: function () {
  26646. return this._effect.isSupported;
  26647. },
  26648. enumerable: true,
  26649. configurable: true
  26650. });
  26651. PostProcess.prototype.apply = function () {
  26652. // Check
  26653. if (!this._effect.isReady())
  26654. return null;
  26655. // States
  26656. this._engine.enableEffect(this._effect);
  26657. this._engine.setState(false);
  26658. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26659. this._engine.setDepthBuffer(false);
  26660. this._engine.setDepthWrite(false);
  26661. // Texture
  26662. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26663. // Parameters
  26664. if (this.onApply) {
  26665. this.onApply(this._effect);
  26666. }
  26667. return this._effect;
  26668. };
  26669. PostProcess.prototype.dispose = function (camera) {
  26670. camera = camera || this._camera;
  26671. if (this._textures.length > 0) {
  26672. for (var i = 0; i < this._textures.length; i++) {
  26673. this._engine._releaseTexture(this._textures.data[i]);
  26674. }
  26675. this._textures.reset();
  26676. }
  26677. if (!camera) {
  26678. return;
  26679. }
  26680. camera.detachPostProcess(this);
  26681. var index = camera._postProcesses.indexOf(this);
  26682. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26683. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26684. }
  26685. };
  26686. return PostProcess;
  26687. })();
  26688. BABYLON.PostProcess = PostProcess;
  26689. })(BABYLON || (BABYLON = {}));
  26690. var BABYLON;
  26691. (function (BABYLON) {
  26692. var PostProcessManager = (function () {
  26693. function PostProcessManager(scene) {
  26694. this._vertexDeclaration = [2];
  26695. this._vertexStrideSize = 2 * 4;
  26696. this._scene = scene;
  26697. }
  26698. PostProcessManager.prototype._prepareBuffers = function () {
  26699. if (this._vertexBuffer) {
  26700. return;
  26701. }
  26702. // VBO
  26703. var vertices = [];
  26704. vertices.push(1, 1);
  26705. vertices.push(-1, 1);
  26706. vertices.push(-1, -1);
  26707. vertices.push(1, -1);
  26708. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26709. // Indices
  26710. var indices = [];
  26711. indices.push(0);
  26712. indices.push(1);
  26713. indices.push(2);
  26714. indices.push(0);
  26715. indices.push(2);
  26716. indices.push(3);
  26717. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26718. };
  26719. // Methods
  26720. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26721. var postProcesses = this._scene.activeCamera._postProcesses;
  26722. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26723. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26724. return false;
  26725. }
  26726. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26727. return true;
  26728. };
  26729. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26730. var engine = this._scene.getEngine();
  26731. for (var index = 0; index < postProcesses.length; index++) {
  26732. if (index < postProcesses.length - 1) {
  26733. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26734. }
  26735. else {
  26736. if (targetTexture) {
  26737. engine.bindFramebuffer(targetTexture);
  26738. }
  26739. else {
  26740. engine.restoreDefaultFramebuffer();
  26741. }
  26742. }
  26743. var pp = postProcesses[index];
  26744. var effect = pp.apply();
  26745. if (effect) {
  26746. if (pp.onBeforeRender) {
  26747. pp.onBeforeRender(effect);
  26748. }
  26749. // VBOs
  26750. this._prepareBuffers();
  26751. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26752. // Draw order
  26753. engine.draw(true, 0, 6);
  26754. if (pp.onAfterRender) {
  26755. pp.onAfterRender(effect);
  26756. }
  26757. }
  26758. }
  26759. // Restore depth buffer
  26760. engine.setDepthBuffer(true);
  26761. engine.setDepthWrite(true);
  26762. };
  26763. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26764. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26765. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26766. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26767. return;
  26768. }
  26769. var engine = this._scene.getEngine();
  26770. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26771. if (index < postProcessesTakenIndices.length - 1) {
  26772. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26773. }
  26774. else {
  26775. if (targetTexture) {
  26776. engine.bindFramebuffer(targetTexture, faceIndex);
  26777. }
  26778. else {
  26779. engine.restoreDefaultFramebuffer();
  26780. }
  26781. }
  26782. if (doNotPresent) {
  26783. break;
  26784. }
  26785. var pp = postProcesses[postProcessesTakenIndices[index]];
  26786. var effect = pp.apply();
  26787. if (effect) {
  26788. if (pp.onBeforeRender) {
  26789. pp.onBeforeRender(effect);
  26790. }
  26791. // VBOs
  26792. this._prepareBuffers();
  26793. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26794. // Draw order
  26795. engine.draw(true, 0, 6);
  26796. if (pp.onAfterRender) {
  26797. pp.onAfterRender(effect);
  26798. }
  26799. }
  26800. }
  26801. // Restore depth buffer
  26802. engine.setDepthBuffer(true);
  26803. engine.setDepthWrite(true);
  26804. };
  26805. PostProcessManager.prototype.dispose = function () {
  26806. if (this._vertexBuffer) {
  26807. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  26808. this._vertexBuffer = null;
  26809. }
  26810. if (this._indexBuffer) {
  26811. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26812. this._indexBuffer = null;
  26813. }
  26814. };
  26815. return PostProcessManager;
  26816. })();
  26817. BABYLON.PostProcessManager = PostProcessManager;
  26818. })(BABYLON || (BABYLON = {}));
  26819. var BABYLON;
  26820. (function (BABYLON) {
  26821. var PassPostProcess = (function (_super) {
  26822. __extends(PassPostProcess, _super);
  26823. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26824. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  26825. }
  26826. return PassPostProcess;
  26827. })(BABYLON.PostProcess);
  26828. BABYLON.PassPostProcess = PassPostProcess;
  26829. })(BABYLON || (BABYLON = {}));
  26830. var BABYLON;
  26831. (function (BABYLON) {
  26832. /**
  26833. * This is a holder class for the physics joint created by the physics plugin.
  26834. * It holds a set of functions to control the underlying joint.
  26835. */
  26836. var PhysicsJoint = (function () {
  26837. function PhysicsJoint(type, jointData) {
  26838. this.type = type;
  26839. this.jointData = jointData;
  26840. jointData.nativeParams = jointData.nativeParams || {};
  26841. }
  26842. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  26843. get: function () {
  26844. return this._physicsJoint;
  26845. },
  26846. set: function (newJoint) {
  26847. if (this._physicsJoint) {
  26848. }
  26849. this._physicsJoint = newJoint;
  26850. },
  26851. enumerable: true,
  26852. configurable: true
  26853. });
  26854. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  26855. set: function (physicsPlugin) {
  26856. this._physicsPlugin = physicsPlugin;
  26857. },
  26858. enumerable: true,
  26859. configurable: true
  26860. });
  26861. /**
  26862. * Execute a function that is physics-plugin specific.
  26863. * @param {Function} func the function that will be executed.
  26864. * It accepts two parameters: the physics world and the physics joint.
  26865. */
  26866. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  26867. func(this._physicsPlugin.world, this._physicsJoint);
  26868. };
  26869. //TODO check if the native joints are the same
  26870. //Joint Types
  26871. PhysicsJoint.DistanceJoint = 0;
  26872. PhysicsJoint.HingeJoint = 1;
  26873. PhysicsJoint.BallAndSocketJoint = 2;
  26874. PhysicsJoint.WheelJoint = 3;
  26875. PhysicsJoint.SliderJoint = 4;
  26876. //OIMO
  26877. PhysicsJoint.PrismaticJoint = 5;
  26878. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  26879. PhysicsJoint.UniversalJoint = 6;
  26880. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  26881. //Cannon
  26882. //Similar to a Ball-Joint. Different in params
  26883. PhysicsJoint.PointToPointJoint = 8;
  26884. //Cannon only at the moment
  26885. PhysicsJoint.SpringJoint = 9;
  26886. return PhysicsJoint;
  26887. })();
  26888. BABYLON.PhysicsJoint = PhysicsJoint;
  26889. /**
  26890. * A class representing a physics distance joint.
  26891. */
  26892. var DistanceJoint = (function (_super) {
  26893. __extends(DistanceJoint, _super);
  26894. function DistanceJoint(jointData) {
  26895. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  26896. }
  26897. /**
  26898. * Update the predefined distance.
  26899. */
  26900. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  26901. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  26902. };
  26903. return DistanceJoint;
  26904. })(PhysicsJoint);
  26905. BABYLON.DistanceJoint = DistanceJoint;
  26906. var MotorEnabledJoint = (function (_super) {
  26907. __extends(MotorEnabledJoint, _super);
  26908. function MotorEnabledJoint(type, jointData) {
  26909. _super.call(this, type, jointData);
  26910. }
  26911. /**
  26912. * Set the motor values.
  26913. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26914. * @param {number} force the force to apply
  26915. * @param {number} maxForce max force for this motor.
  26916. */
  26917. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  26918. this._physicsPlugin.setMotor(this, force, maxForce);
  26919. };
  26920. /**
  26921. * Set the motor's limits.
  26922. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26923. */
  26924. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  26925. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  26926. };
  26927. return MotorEnabledJoint;
  26928. })(PhysicsJoint);
  26929. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  26930. /**
  26931. * This class represents a single hinge physics joint
  26932. */
  26933. var HingeJoint = (function (_super) {
  26934. __extends(HingeJoint, _super);
  26935. function HingeJoint(jointData) {
  26936. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  26937. }
  26938. /**
  26939. * Set the motor values.
  26940. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26941. * @param {number} force the force to apply
  26942. * @param {number} maxForce max force for this motor.
  26943. */
  26944. HingeJoint.prototype.setMotor = function (force, maxForce) {
  26945. this._physicsPlugin.setMotor(this, force, maxForce);
  26946. };
  26947. /**
  26948. * Set the motor's limits.
  26949. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26950. */
  26951. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  26952. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  26953. };
  26954. return HingeJoint;
  26955. })(MotorEnabledJoint);
  26956. BABYLON.HingeJoint = HingeJoint;
  26957. /**
  26958. * This class represents a dual hinge physics joint (same as wheel joint)
  26959. */
  26960. var Hinge2Joint = (function (_super) {
  26961. __extends(Hinge2Joint, _super);
  26962. function Hinge2Joint(jointData) {
  26963. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  26964. }
  26965. /**
  26966. * Set the motor values.
  26967. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26968. * @param {number} force the force to apply
  26969. * @param {number} maxForce max force for this motor.
  26970. * @param {motorIndex} the motor's index, 0 or 1.
  26971. */
  26972. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  26973. if (motorIndex === void 0) { motorIndex = 0; }
  26974. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  26975. };
  26976. /**
  26977. * Set the motor limits.
  26978. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26979. * @param {number} upperLimit the upper limit
  26980. * @param {number} lowerLimit lower limit
  26981. * @param {motorIndex} the motor's index, 0 or 1.
  26982. */
  26983. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  26984. if (motorIndex === void 0) { motorIndex = 0; }
  26985. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  26986. };
  26987. return Hinge2Joint;
  26988. })(MotorEnabledJoint);
  26989. BABYLON.Hinge2Joint = Hinge2Joint;
  26990. })(BABYLON || (BABYLON = {}));
  26991. var BABYLON;
  26992. (function (BABYLON) {
  26993. var PhysicsImpostor = (function () {
  26994. function PhysicsImpostor(object, type, _options, _scene) {
  26995. var _this = this;
  26996. if (_options === void 0) { _options = { mass: 0 }; }
  26997. this.object = object;
  26998. this.type = type;
  26999. this._options = _options;
  27000. this._scene = _scene;
  27001. this._bodyUpdateRequired = false;
  27002. this._onBeforePhysicsStepCallbacks = new Array();
  27003. this._onAfterPhysicsStepCallbacks = new Array();
  27004. this._onPhysicsCollideCallbacks = [];
  27005. this._deltaPosition = BABYLON.Vector3.Zero();
  27006. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  27007. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  27008. /**
  27009. * this function is executed by the physics engine.
  27010. */
  27011. this.beforeStep = function () {
  27012. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  27013. //conjugate deltaRotation
  27014. if (_this._deltaRotationConjugated) {
  27015. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  27016. }
  27017. else {
  27018. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  27019. }
  27020. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  27021. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  27022. func(_this);
  27023. });
  27024. };
  27025. /**
  27026. * this function is executed by the physics engine.
  27027. */
  27028. this.afterStep = function () {
  27029. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  27030. func(_this);
  27031. });
  27032. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  27033. _this.object.position.addInPlace(_this._deltaPosition);
  27034. if (_this._deltaRotation) {
  27035. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  27036. }
  27037. };
  27038. //event and body object due to cannon's event-based architecture.
  27039. this.onCollide = function (e) {
  27040. if (!_this._onPhysicsCollideCallbacks.length)
  27041. return;
  27042. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  27043. if (otherImpostor) {
  27044. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  27045. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  27046. }).forEach(function (obj) {
  27047. obj.callback(_this, otherImpostor);
  27048. });
  27049. }
  27050. };
  27051. //sanity check!
  27052. if (!this.object) {
  27053. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  27054. return;
  27055. }
  27056. //legacy support for old syntax.
  27057. if (!this._scene && object.getScene) {
  27058. this._scene = object.getScene();
  27059. }
  27060. this._physicsEngine = this._scene.getPhysicsEngine();
  27061. if (!this._physicsEngine) {
  27062. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  27063. }
  27064. else {
  27065. //set the object's quaternion, if not set
  27066. if (!this.object.rotationQuaternion) {
  27067. if (this.object.rotation) {
  27068. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  27069. }
  27070. else {
  27071. this.object.rotationQuaternion = new BABYLON.Quaternion();
  27072. }
  27073. }
  27074. //default options params
  27075. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  27076. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  27077. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  27078. this._joints = [];
  27079. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27080. if (!this.object.parent) {
  27081. this._init();
  27082. }
  27083. }
  27084. }
  27085. /**
  27086. * This function will completly initialize this impostor.
  27087. * It will create a new body - but only if this mesh has no parent.
  27088. * If it has, this impostor will not be used other than to define the impostor
  27089. * of the child mesh.
  27090. */
  27091. PhysicsImpostor.prototype._init = function () {
  27092. this._physicsEngine.removeImpostor(this);
  27093. this.physicsBody = null;
  27094. this._parent = this._parent || this._getPhysicsParent();
  27095. if (!this.parent) {
  27096. this._physicsEngine.addImpostor(this);
  27097. }
  27098. };
  27099. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27100. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27101. var parentMesh = this.object.parent;
  27102. return parentMesh.physicsImpostor;
  27103. }
  27104. return;
  27105. };
  27106. /**
  27107. * Should a new body be generated.
  27108. */
  27109. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27110. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27111. };
  27112. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27113. this.forceUpdate();
  27114. };
  27115. /**
  27116. * Force a regeneration of this or the parent's impostor's body.
  27117. * Use under cautious - This will remove all joints already implemented.
  27118. */
  27119. PhysicsImpostor.prototype.forceUpdate = function () {
  27120. this._init();
  27121. if (this.parent) {
  27122. this.parent.forceUpdate();
  27123. }
  27124. };
  27125. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27126. /*public get mesh(): AbstractMesh {
  27127. return this._mesh;
  27128. }*/
  27129. /**
  27130. * Gets the body that holds this impostor. Either its own, or its parent.
  27131. */
  27132. get: function () {
  27133. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27134. },
  27135. /**
  27136. * Set the physics body. Used mainly by the physics engine/plugin
  27137. */
  27138. set: function (physicsBody) {
  27139. if (this._physicsBody) {
  27140. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27141. }
  27142. this._physicsBody = physicsBody;
  27143. this.resetUpdateFlags();
  27144. },
  27145. enumerable: true,
  27146. configurable: true
  27147. });
  27148. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  27149. get: function () {
  27150. return this._parent;
  27151. },
  27152. enumerable: true,
  27153. configurable: true
  27154. });
  27155. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  27156. this._bodyUpdateRequired = false;
  27157. };
  27158. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27159. if (this.object.getBoundingInfo) {
  27160. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27161. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27162. }
  27163. else {
  27164. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27165. }
  27166. };
  27167. PhysicsImpostor.prototype.getObjectCenter = function () {
  27168. if (this.object.getBoundingInfo) {
  27169. return this.object.getBoundingInfo().boundingBox.center;
  27170. }
  27171. else {
  27172. return this.object.position;
  27173. }
  27174. };
  27175. /**
  27176. * Get a specific parametes from the options parameter.
  27177. */
  27178. PhysicsImpostor.prototype.getParam = function (paramName) {
  27179. return this._options[paramName];
  27180. };
  27181. /**
  27182. * Sets a specific parameter in the options given to the physics plugin
  27183. */
  27184. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27185. this._options[paramName] = value;
  27186. this._bodyUpdateRequired = true;
  27187. };
  27188. /**
  27189. * Specifically change the body's mass option. Won't recreate the physics body object
  27190. */
  27191. PhysicsImpostor.prototype.setMass = function (mass) {
  27192. if (this.getParam("mass") !== mass) {
  27193. this.setParam("mass", mass);
  27194. }
  27195. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27196. };
  27197. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27198. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27199. };
  27200. /**
  27201. * Set the body's linear velocity.
  27202. */
  27203. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27204. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27205. };
  27206. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27207. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27208. };
  27209. /**
  27210. * Set the body's linear velocity.
  27211. */
  27212. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27213. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27214. };
  27215. /**
  27216. * Execute a function with the physics plugin native code.
  27217. * Provide a function the will have two variables - the world object and the physics body object.
  27218. */
  27219. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27220. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27221. };
  27222. /**
  27223. * Register a function that will be executed before the physics world is stepping forward.
  27224. */
  27225. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27226. this._onBeforePhysicsStepCallbacks.push(func);
  27227. };
  27228. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27229. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27230. if (index > -1) {
  27231. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27232. }
  27233. else {
  27234. BABYLON.Tools.Warn("Function to remove was not found");
  27235. }
  27236. };
  27237. /**
  27238. * Register a function that will be executed after the physics step
  27239. */
  27240. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27241. this._onAfterPhysicsStepCallbacks.push(func);
  27242. };
  27243. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27244. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27245. if (index > -1) {
  27246. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27247. }
  27248. else {
  27249. BABYLON.Tools.Warn("Function to remove was not found");
  27250. }
  27251. };
  27252. /**
  27253. * register a function that will be executed when this impostor collides against a different body.
  27254. */
  27255. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27256. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27257. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27258. };
  27259. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27260. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27261. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27262. if (index > -1) {
  27263. this._onPhysicsCollideCallbacks.splice(index, 1);
  27264. }
  27265. else {
  27266. BABYLON.Tools.Warn("Function to remove was not found");
  27267. }
  27268. };
  27269. /**
  27270. * Apply a force
  27271. */
  27272. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27273. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27274. };
  27275. /**
  27276. * Apply an impulse
  27277. */
  27278. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27279. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27280. };
  27281. /**
  27282. * A help function to create a joint.
  27283. */
  27284. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27285. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27286. this.addJoint(otherImpostor, joint);
  27287. };
  27288. /**
  27289. * Add a joint to this impostor with a different impostor.
  27290. */
  27291. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27292. this._joints.push({
  27293. otherImpostor: otherImpostor,
  27294. joint: joint
  27295. });
  27296. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27297. };
  27298. /**
  27299. * Will keep this body still, in a sleep mode.
  27300. */
  27301. PhysicsImpostor.prototype.sleep = function () {
  27302. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27303. };
  27304. /**
  27305. * Wake the body up.
  27306. */
  27307. PhysicsImpostor.prototype.wakeUp = function () {
  27308. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27309. };
  27310. PhysicsImpostor.prototype.clone = function (newObject) {
  27311. if (!newObject)
  27312. return null;
  27313. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27314. };
  27315. PhysicsImpostor.prototype.dispose = function () {
  27316. var _this = this;
  27317. this._joints.forEach(function (j) {
  27318. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  27319. });
  27320. //dispose the physics body
  27321. this._physicsEngine.removeImpostor(this);
  27322. if (this.parent) {
  27323. this.parent.forceUpdate();
  27324. }
  27325. else {
  27326. }
  27327. };
  27328. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27329. this._deltaPosition.copyFrom(position);
  27330. };
  27331. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27332. if (!this._deltaRotation) {
  27333. this._deltaRotation = new BABYLON.Quaternion();
  27334. }
  27335. this._deltaRotation.copyFrom(rotation);
  27336. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27337. };
  27338. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27339. //Impostor types
  27340. PhysicsImpostor.NoImpostor = 0;
  27341. PhysicsImpostor.SphereImpostor = 1;
  27342. PhysicsImpostor.BoxImpostor = 2;
  27343. PhysicsImpostor.PlaneImpostor = 3;
  27344. PhysicsImpostor.MeshImpostor = 4;
  27345. PhysicsImpostor.CylinderImpostor = 7;
  27346. PhysicsImpostor.ParticleImpostor = 8;
  27347. PhysicsImpostor.HeightmapImpostor = 9;
  27348. return PhysicsImpostor;
  27349. })();
  27350. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27351. })(BABYLON || (BABYLON = {}));
  27352. var BABYLON;
  27353. (function (BABYLON) {
  27354. var PhysicsEngine = (function () {
  27355. function PhysicsEngine(gravity, _physicsPlugin) {
  27356. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27357. this._physicsPlugin = _physicsPlugin;
  27358. //new methods and parameters
  27359. this._impostors = [];
  27360. this._joints = [];
  27361. if (!this._physicsPlugin.isSupported()) {
  27362. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27363. + "Please make sure it is included.");
  27364. }
  27365. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27366. this.setGravity(gravity);
  27367. this.setTimeStep();
  27368. }
  27369. PhysicsEngine.prototype.setGravity = function (gravity) {
  27370. this.gravity = gravity;
  27371. this._physicsPlugin.setGravity(this.gravity);
  27372. };
  27373. /**
  27374. * Set the time step of the physics engine.
  27375. * default is 1/60.
  27376. * To slow it down, enter 1/600 for example.
  27377. * To speed it up, 1/30
  27378. * @param {number} newTimeStep the new timestep to apply to this world.
  27379. */
  27380. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27381. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27382. this._physicsPlugin.setTimeStep(newTimeStep);
  27383. };
  27384. PhysicsEngine.prototype.dispose = function () {
  27385. this._impostors.forEach(function (impostor) {
  27386. impostor.dispose();
  27387. });
  27388. this._physicsPlugin.dispose();
  27389. };
  27390. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27391. return this._physicsPlugin.name;
  27392. };
  27393. /**
  27394. * Adding a new impostor for the impostor tracking.
  27395. * This will be done by the impostor itself.
  27396. * @param {PhysicsImpostor} impostor the impostor to add
  27397. */
  27398. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27399. impostor.uniqueId = this._impostors.push(impostor);
  27400. //if no parent, generate the body
  27401. if (!impostor.parent) {
  27402. this._physicsPlugin.generatePhysicsBody(impostor);
  27403. }
  27404. };
  27405. /**
  27406. * Remove an impostor from the engine.
  27407. * This impostor and its mesh will not longer be updated by the physics engine.
  27408. * @param {PhysicsImpostor} impostor the impostor to remove
  27409. */
  27410. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27411. var index = this._impostors.indexOf(impostor);
  27412. if (index > -1) {
  27413. var removed = this._impostors.splice(index, 1);
  27414. //Is it needed?
  27415. if (removed.length) {
  27416. //this will also remove it from the world.
  27417. removed[0].physicsBody = null;
  27418. }
  27419. }
  27420. };
  27421. /**
  27422. * Add a joint to the physics engine
  27423. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27424. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27425. * @param {PhysicsJoint} the joint that will connect both impostors.
  27426. */
  27427. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27428. var impostorJoint = {
  27429. mainImpostor: mainImpostor,
  27430. connectedImpostor: connectedImpostor,
  27431. joint: joint
  27432. };
  27433. joint.physicsPlugin = this._physicsPlugin;
  27434. this._joints.push(impostorJoint);
  27435. this._physicsPlugin.generateJoint(impostorJoint);
  27436. };
  27437. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27438. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27439. return (impostorJoint.connectedImpostor === connectedImpostor
  27440. && impostorJoint.joint === joint
  27441. && impostorJoint.mainImpostor === mainImpostor);
  27442. });
  27443. if (matchingJoints.length) {
  27444. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27445. }
  27446. };
  27447. /**
  27448. * Called by the scene. no need to call it.
  27449. */
  27450. PhysicsEngine.prototype._step = function (delta) {
  27451. var _this = this;
  27452. //check if any mesh has no body / requires an update
  27453. this._impostors.forEach(function (impostor) {
  27454. if (impostor.isBodyInitRequired()) {
  27455. _this._physicsPlugin.generatePhysicsBody(impostor);
  27456. }
  27457. });
  27458. if (delta > 0.1) {
  27459. delta = 0.1;
  27460. }
  27461. else if (delta <= 0) {
  27462. delta = 1.0 / 60.0;
  27463. }
  27464. this._physicsPlugin.executeStep(delta, this._impostors);
  27465. };
  27466. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27467. return this._physicsPlugin;
  27468. };
  27469. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27470. for (var i = 0; i < this._impostors.length; ++i) {
  27471. if (this._impostors[i].object === object) {
  27472. return this._impostors[i];
  27473. }
  27474. }
  27475. };
  27476. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27477. for (var i = 0; i < this._impostors.length; ++i) {
  27478. if (this._impostors[i].physicsBody === body) {
  27479. return this._impostors[i];
  27480. }
  27481. }
  27482. };
  27483. // Statics, Legacy support.
  27484. /**
  27485. * @Deprecated
  27486. *
  27487. */
  27488. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27489. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27490. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27491. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27492. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27493. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27494. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27495. PhysicsEngine.CapsuleImpostor = -1;
  27496. PhysicsEngine.ConeImpostor = -1;
  27497. PhysicsEngine.ConvexHullImpostor = -1;
  27498. PhysicsEngine.Epsilon = 0.001;
  27499. return PhysicsEngine;
  27500. })();
  27501. BABYLON.PhysicsEngine = PhysicsEngine;
  27502. })(BABYLON || (BABYLON = {}));
  27503. var BABYLON;
  27504. (function (BABYLON) {
  27505. var VertexData = (function () {
  27506. function VertexData() {
  27507. }
  27508. VertexData.prototype.set = function (data, kind) {
  27509. switch (kind) {
  27510. case BABYLON.VertexBuffer.PositionKind:
  27511. this.positions = data;
  27512. break;
  27513. case BABYLON.VertexBuffer.NormalKind:
  27514. this.normals = data;
  27515. break;
  27516. case BABYLON.VertexBuffer.UVKind:
  27517. this.uvs = data;
  27518. break;
  27519. case BABYLON.VertexBuffer.UV2Kind:
  27520. this.uvs2 = data;
  27521. break;
  27522. case BABYLON.VertexBuffer.UV3Kind:
  27523. this.uvs3 = data;
  27524. break;
  27525. case BABYLON.VertexBuffer.UV4Kind:
  27526. this.uvs4 = data;
  27527. break;
  27528. case BABYLON.VertexBuffer.UV5Kind:
  27529. this.uvs5 = data;
  27530. break;
  27531. case BABYLON.VertexBuffer.UV6Kind:
  27532. this.uvs6 = data;
  27533. break;
  27534. case BABYLON.VertexBuffer.ColorKind:
  27535. this.colors = data;
  27536. break;
  27537. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27538. this.matricesIndices = data;
  27539. break;
  27540. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27541. this.matricesWeights = data;
  27542. break;
  27543. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27544. this.matricesIndicesExtra = data;
  27545. break;
  27546. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27547. this.matricesWeightsExtra = data;
  27548. break;
  27549. }
  27550. };
  27551. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27552. this._applyTo(mesh, updatable);
  27553. };
  27554. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27555. this._applyTo(geometry, updatable);
  27556. };
  27557. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27558. this._update(mesh);
  27559. };
  27560. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27561. this._update(geometry);
  27562. };
  27563. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27564. if (this.positions) {
  27565. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27566. }
  27567. if (this.normals) {
  27568. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27569. }
  27570. if (this.uvs) {
  27571. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27572. }
  27573. if (this.uvs2) {
  27574. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27575. }
  27576. if (this.uvs3) {
  27577. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27578. }
  27579. if (this.uvs4) {
  27580. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27581. }
  27582. if (this.uvs5) {
  27583. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27584. }
  27585. if (this.uvs6) {
  27586. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27587. }
  27588. if (this.colors) {
  27589. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27590. }
  27591. if (this.matricesIndices) {
  27592. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27593. }
  27594. if (this.matricesWeights) {
  27595. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27596. }
  27597. if (this.matricesIndicesExtra) {
  27598. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27599. }
  27600. if (this.matricesWeightsExtra) {
  27601. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27602. }
  27603. if (this.indices) {
  27604. meshOrGeometry.setIndices(this.indices);
  27605. }
  27606. };
  27607. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27608. if (this.positions) {
  27609. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27610. }
  27611. if (this.normals) {
  27612. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27613. }
  27614. if (this.uvs) {
  27615. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27616. }
  27617. if (this.uvs2) {
  27618. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27619. }
  27620. if (this.uvs3) {
  27621. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27622. }
  27623. if (this.uvs4) {
  27624. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27625. }
  27626. if (this.uvs5) {
  27627. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27628. }
  27629. if (this.uvs6) {
  27630. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27631. }
  27632. if (this.colors) {
  27633. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27634. }
  27635. if (this.matricesIndices) {
  27636. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27637. }
  27638. if (this.matricesWeights) {
  27639. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27640. }
  27641. if (this.matricesIndicesExtra) {
  27642. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27643. }
  27644. if (this.matricesWeightsExtra) {
  27645. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27646. }
  27647. if (this.indices) {
  27648. meshOrGeometry.setIndices(this.indices);
  27649. }
  27650. };
  27651. VertexData.prototype.transform = function (matrix) {
  27652. var transformed = BABYLON.Vector3.Zero();
  27653. var index;
  27654. if (this.positions) {
  27655. var position = BABYLON.Vector3.Zero();
  27656. for (index = 0; index < this.positions.length; index += 3) {
  27657. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27658. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27659. this.positions[index] = transformed.x;
  27660. this.positions[index + 1] = transformed.y;
  27661. this.positions[index + 2] = transformed.z;
  27662. }
  27663. }
  27664. if (this.normals) {
  27665. var normal = BABYLON.Vector3.Zero();
  27666. for (index = 0; index < this.normals.length; index += 3) {
  27667. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27668. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27669. this.normals[index] = transformed.x;
  27670. this.normals[index + 1] = transformed.y;
  27671. this.normals[index + 2] = transformed.z;
  27672. }
  27673. }
  27674. };
  27675. VertexData.prototype.merge = function (other) {
  27676. if (other.indices) {
  27677. if (!this.indices) {
  27678. this.indices = [];
  27679. }
  27680. var offset = this.positions ? this.positions.length / 3 : 0;
  27681. for (var index = 0; index < other.indices.length; index++) {
  27682. //TODO check type - if Int32Array!
  27683. this.indices.push(other.indices[index] + offset);
  27684. }
  27685. }
  27686. this.positions = this._mergeElement(this.positions, other.positions);
  27687. this.normals = this._mergeElement(this.normals, other.normals);
  27688. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27689. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27690. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27691. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27692. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27693. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27694. this.colors = this._mergeElement(this.colors, other.colors);
  27695. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27696. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27697. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27698. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27699. };
  27700. VertexData.prototype._mergeElement = function (source, other) {
  27701. if (!other)
  27702. return source;
  27703. if (!source)
  27704. return other;
  27705. var len = other.length + source.length;
  27706. var isSrcTypedArray = source instanceof Float32Array;
  27707. var isOthTypedArray = other instanceof Float32Array;
  27708. // use non-loop method when the source is Float32Array
  27709. if (isSrcTypedArray) {
  27710. var ret32 = new Float32Array(len);
  27711. ret32.set(source);
  27712. ret32.set(other, source.length);
  27713. return ret32;
  27714. }
  27715. else if (!isOthTypedArray) {
  27716. return source.concat(other);
  27717. }
  27718. else {
  27719. var ret = source.slice(0); // copy source to a separate array
  27720. for (var i = 0, len = other.length; i < len; i++) {
  27721. ret.push(other[i]);
  27722. }
  27723. return ret;
  27724. }
  27725. };
  27726. VertexData.prototype.serialize = function () {
  27727. var serializationObject = this.serialize();
  27728. if (this.positions) {
  27729. serializationObject.positions = this.positions;
  27730. }
  27731. if (this.normals) {
  27732. serializationObject.normals = this.normals;
  27733. }
  27734. if (this.uvs) {
  27735. serializationObject.uvs = this.uvs;
  27736. }
  27737. if (this.uvs2) {
  27738. serializationObject.uvs2 = this.uvs2;
  27739. }
  27740. if (this.uvs3) {
  27741. serializationObject.uvs3 = this.uvs3;
  27742. }
  27743. if (this.uvs4) {
  27744. serializationObject.uvs4 = this.uvs4;
  27745. }
  27746. if (this.uvs5) {
  27747. serializationObject.uvs5 = this.uvs5;
  27748. }
  27749. if (this.uvs6) {
  27750. serializationObject.uvs6 = this.uvs6;
  27751. }
  27752. if (this.colors) {
  27753. serializationObject.colors = this.colors;
  27754. }
  27755. if (this.matricesIndices) {
  27756. serializationObject.matricesIndices = this.matricesIndices;
  27757. serializationObject.matricesIndices._isExpanded = true;
  27758. }
  27759. if (this.matricesWeights) {
  27760. serializationObject.matricesWeights = this.matricesWeights;
  27761. }
  27762. if (this.matricesIndicesExtra) {
  27763. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27764. serializationObject.matricesIndicesExtra._isExpanded = true;
  27765. }
  27766. if (this.matricesWeightsExtra) {
  27767. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27768. }
  27769. serializationObject.indices = this.indices;
  27770. return serializationObject;
  27771. };
  27772. // Statics
  27773. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27774. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27775. };
  27776. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  27777. return VertexData._ExtractFrom(geometry, copyWhenShared);
  27778. };
  27779. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  27780. var result = new VertexData();
  27781. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27782. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  27783. }
  27784. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27785. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  27786. }
  27787. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27788. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  27789. }
  27790. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27791. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  27792. }
  27793. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27794. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  27795. }
  27796. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27797. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  27798. }
  27799. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27800. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  27801. }
  27802. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27803. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  27804. }
  27805. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27806. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  27807. }
  27808. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27809. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  27810. }
  27811. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27812. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  27813. }
  27814. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27815. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  27816. }
  27817. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27818. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  27819. }
  27820. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27821. return result;
  27822. };
  27823. VertexData.CreateRibbon = function (options) {
  27824. var pathArray = options.pathArray;
  27825. var closeArray = options.closeArray || false;
  27826. var closePath = options.closePath || false;
  27827. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27828. var offset = options.offset || defaultOffset;
  27829. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27830. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27831. var positions = [];
  27832. var indices = [];
  27833. var normals = [];
  27834. var uvs = [];
  27835. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27836. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27837. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27838. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27839. var minlg; // minimal length among all paths from pathArray
  27840. var lg = []; // array of path lengths : nb of vertex per path
  27841. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27842. var p; // path iterator
  27843. var i; // point iterator
  27844. var j; // point iterator
  27845. // if single path in pathArray
  27846. if (pathArray.length < 2) {
  27847. var ar1 = [];
  27848. var ar2 = [];
  27849. for (i = 0; i < pathArray[0].length - offset; i++) {
  27850. ar1.push(pathArray[0][i]);
  27851. ar2.push(pathArray[0][i + offset]);
  27852. }
  27853. pathArray = [ar1, ar2];
  27854. }
  27855. // positions and horizontal distances (u)
  27856. var idc = 0;
  27857. var closePathCorr = (closePath) ? 1 : 0;
  27858. var path;
  27859. var l;
  27860. minlg = pathArray[0].length;
  27861. var vectlg;
  27862. var dist;
  27863. for (p = 0; p < pathArray.length; p++) {
  27864. uTotalDistance[p] = 0;
  27865. us[p] = [0];
  27866. path = pathArray[p];
  27867. l = path.length;
  27868. minlg = (minlg < l) ? minlg : l;
  27869. j = 0;
  27870. while (j < l) {
  27871. positions.push(path[j].x, path[j].y, path[j].z);
  27872. if (j > 0) {
  27873. vectlg = path[j].subtract(path[j - 1]).length();
  27874. dist = vectlg + uTotalDistance[p];
  27875. us[p].push(dist);
  27876. uTotalDistance[p] = dist;
  27877. }
  27878. j++;
  27879. }
  27880. if (closePath) {
  27881. j--;
  27882. positions.push(path[0].x, path[0].y, path[0].z);
  27883. vectlg = path[j].subtract(path[0]).length();
  27884. dist = vectlg + uTotalDistance[p];
  27885. us[p].push(dist);
  27886. uTotalDistance[p] = dist;
  27887. }
  27888. lg[p] = l + closePathCorr;
  27889. idx[p] = idc;
  27890. idc += (l + closePathCorr);
  27891. }
  27892. // vertical distances (v)
  27893. var path1;
  27894. var path2;
  27895. var vertex1;
  27896. var vertex2;
  27897. for (i = 0; i < minlg + closePathCorr; i++) {
  27898. vTotalDistance[i] = 0;
  27899. vs[i] = [0];
  27900. for (p = 0; p < pathArray.length - 1; p++) {
  27901. path1 = pathArray[p];
  27902. path2 = pathArray[p + 1];
  27903. if (i === minlg) {
  27904. vertex1 = path1[0];
  27905. vertex2 = path2[0];
  27906. }
  27907. else {
  27908. vertex1 = path1[i];
  27909. vertex2 = path2[i];
  27910. }
  27911. vectlg = vertex2.subtract(vertex1).length();
  27912. dist = vectlg + vTotalDistance[i];
  27913. vs[i].push(dist);
  27914. vTotalDistance[i] = dist;
  27915. }
  27916. if (closeArray) {
  27917. path1 = pathArray[p];
  27918. path2 = pathArray[0];
  27919. if (i === minlg) {
  27920. vertex2 = path2[0];
  27921. }
  27922. vectlg = vertex2.subtract(vertex1).length();
  27923. dist = vectlg + vTotalDistance[i];
  27924. vTotalDistance[i] = dist;
  27925. }
  27926. }
  27927. // uvs
  27928. var u;
  27929. var v;
  27930. for (p = 0; p < pathArray.length; p++) {
  27931. for (i = 0; i < minlg + closePathCorr; i++) {
  27932. u = us[p][i] / uTotalDistance[p];
  27933. v = vs[i][p] / vTotalDistance[i];
  27934. uvs.push(u, v);
  27935. }
  27936. }
  27937. // indices
  27938. p = 0; // path index
  27939. var pi = 0; // positions array index
  27940. var l1 = lg[p] - 1; // path1 length
  27941. var l2 = lg[p + 1] - 1; // path2 length
  27942. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27943. var shft = idx[1] - idx[0]; // shift
  27944. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27945. while (pi <= min && p < path1nb) {
  27946. // 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
  27947. indices.push(pi, pi + shft, pi + 1);
  27948. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27949. pi += 1;
  27950. if (pi === min) {
  27951. p++;
  27952. if (p === lg.length - 1) {
  27953. shft = idx[0] - idx[p];
  27954. l1 = lg[p] - 1;
  27955. l2 = lg[0] - 1;
  27956. }
  27957. else {
  27958. shft = idx[p + 1] - idx[p];
  27959. l1 = lg[p] - 1;
  27960. l2 = lg[p + 1] - 1;
  27961. }
  27962. pi = idx[p];
  27963. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27964. }
  27965. }
  27966. // normals
  27967. VertexData.ComputeNormals(positions, indices, normals);
  27968. if (closePath) {
  27969. var indexFirst = 0;
  27970. var indexLast = 0;
  27971. for (p = 0; p < pathArray.length; p++) {
  27972. indexFirst = idx[p] * 3;
  27973. if (p + 1 < pathArray.length) {
  27974. indexLast = (idx[p + 1] - 1) * 3;
  27975. }
  27976. else {
  27977. indexLast = normals.length - 3;
  27978. }
  27979. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27980. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27981. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27982. normals[indexLast] = normals[indexFirst];
  27983. normals[indexLast + 1] = normals[indexFirst + 1];
  27984. normals[indexLast + 2] = normals[indexFirst + 2];
  27985. }
  27986. }
  27987. // sides
  27988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27989. // Result
  27990. var vertexData = new VertexData();
  27991. vertexData.indices = indices;
  27992. vertexData.positions = positions;
  27993. vertexData.normals = normals;
  27994. vertexData.uvs = uvs;
  27995. if (closePath) {
  27996. vertexData._idx = idx;
  27997. }
  27998. return vertexData;
  27999. };
  28000. VertexData.CreateBox = function (options) {
  28001. var normalsSource = [
  28002. new BABYLON.Vector3(0, 0, 1),
  28003. new BABYLON.Vector3(0, 0, -1),
  28004. new BABYLON.Vector3(1, 0, 0),
  28005. new BABYLON.Vector3(-1, 0, 0),
  28006. new BABYLON.Vector3(0, 1, 0),
  28007. new BABYLON.Vector3(0, -1, 0)
  28008. ];
  28009. var indices = [];
  28010. var positions = [];
  28011. var normals = [];
  28012. var uvs = [];
  28013. var width = options.width || options.size || 1;
  28014. var height = options.height || options.size || 1;
  28015. var depth = options.depth || options.size || 1;
  28016. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28017. var faceUV = options.faceUV || new Array(6);
  28018. var faceColors = options.faceColors;
  28019. var colors = [];
  28020. // default face colors and UV if undefined
  28021. for (var f = 0; f < 6; f++) {
  28022. if (faceUV[f] === undefined) {
  28023. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28024. }
  28025. if (faceColors && faceColors[f] === undefined) {
  28026. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28027. }
  28028. }
  28029. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28030. // Create each face in turn.
  28031. for (var index = 0; index < normalsSource.length; index++) {
  28032. var normal = normalsSource[index];
  28033. // Get two vectors perpendicular to the face normal and to each other.
  28034. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28035. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28036. // Six indices (two triangles) per face.
  28037. var verticesLength = positions.length / 3;
  28038. indices.push(verticesLength);
  28039. indices.push(verticesLength + 1);
  28040. indices.push(verticesLength + 2);
  28041. indices.push(verticesLength);
  28042. indices.push(verticesLength + 2);
  28043. indices.push(verticesLength + 3);
  28044. // Four vertices per face.
  28045. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28046. positions.push(vertex.x, vertex.y, vertex.z);
  28047. normals.push(normal.x, normal.y, normal.z);
  28048. uvs.push(faceUV[index].z, faceUV[index].w);
  28049. if (faceColors) {
  28050. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28051. }
  28052. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28053. positions.push(vertex.x, vertex.y, vertex.z);
  28054. normals.push(normal.x, normal.y, normal.z);
  28055. uvs.push(faceUV[index].x, faceUV[index].w);
  28056. if (faceColors) {
  28057. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28058. }
  28059. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28060. positions.push(vertex.x, vertex.y, vertex.z);
  28061. normals.push(normal.x, normal.y, normal.z);
  28062. uvs.push(faceUV[index].x, faceUV[index].y);
  28063. if (faceColors) {
  28064. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28065. }
  28066. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28067. positions.push(vertex.x, vertex.y, vertex.z);
  28068. normals.push(normal.x, normal.y, normal.z);
  28069. uvs.push(faceUV[index].z, faceUV[index].y);
  28070. if (faceColors) {
  28071. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28072. }
  28073. }
  28074. // sides
  28075. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28076. // Result
  28077. var vertexData = new VertexData();
  28078. vertexData.indices = indices;
  28079. vertexData.positions = positions;
  28080. vertexData.normals = normals;
  28081. vertexData.uvs = uvs;
  28082. if (faceColors) {
  28083. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28084. vertexData.colors = totalColors;
  28085. }
  28086. return vertexData;
  28087. };
  28088. VertexData.CreateSphere = function (options) {
  28089. var segments = options.segments || 32;
  28090. var diameterX = options.diameterX || options.diameter || 1;
  28091. var diameterY = options.diameterY || options.diameter || 1;
  28092. var diameterZ = options.diameterZ || options.diameter || 1;
  28093. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28094. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28095. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28096. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28097. var totalZRotationSteps = 2 + segments;
  28098. var totalYRotationSteps = 2 * totalZRotationSteps;
  28099. var indices = [];
  28100. var positions = [];
  28101. var normals = [];
  28102. var uvs = [];
  28103. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28104. var normalizedZ = zRotationStep / totalZRotationSteps;
  28105. var angleZ = normalizedZ * Math.PI * slice;
  28106. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28107. var normalizedY = yRotationStep / totalYRotationSteps;
  28108. var angleY = normalizedY * Math.PI * 2 * arc;
  28109. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28110. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28111. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28112. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28113. var vertex = complete.multiply(radius);
  28114. var normal = complete.divide(radius).normalize();
  28115. positions.push(vertex.x, vertex.y, vertex.z);
  28116. normals.push(normal.x, normal.y, normal.z);
  28117. uvs.push(normalizedY, normalizedZ);
  28118. }
  28119. if (zRotationStep > 0) {
  28120. var verticesCount = positions.length / 3;
  28121. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28122. indices.push((firstIndex));
  28123. indices.push((firstIndex + 1));
  28124. indices.push(firstIndex + totalYRotationSteps + 1);
  28125. indices.push((firstIndex + totalYRotationSteps + 1));
  28126. indices.push((firstIndex + 1));
  28127. indices.push((firstIndex + totalYRotationSteps + 2));
  28128. }
  28129. }
  28130. }
  28131. // Sides
  28132. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28133. // Result
  28134. var vertexData = new VertexData();
  28135. vertexData.indices = indices;
  28136. vertexData.positions = positions;
  28137. vertexData.normals = normals;
  28138. vertexData.uvs = uvs;
  28139. return vertexData;
  28140. };
  28141. // Cylinder and cone
  28142. VertexData.CreateCylinder = function (options) {
  28143. var height = options.height || 2;
  28144. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28145. var diameterBottom = options.diameterBottom || options.diameter || 1;
  28146. var tessellation = options.tessellation || 24;
  28147. var subdivisions = options.subdivisions || 1;
  28148. var hasRings = options.hasRings;
  28149. var enclose = options.enclose;
  28150. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28151. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28152. var faceUV = options.faceUV || new Array(3);
  28153. var faceColors = options.faceColors;
  28154. // default face colors and UV if undefined
  28155. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28156. var ringNb = (hasRings) ? subdivisions : 1;
  28157. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28158. var f;
  28159. for (f = 0; f < surfaceNb; f++) {
  28160. if (faceColors && faceColors[f] === undefined) {
  28161. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28162. }
  28163. }
  28164. for (f = 0; f < surfaceNb; f++) {
  28165. if (faceUV && faceUV[f] === undefined) {
  28166. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28167. }
  28168. }
  28169. var indices = [];
  28170. var positions = [];
  28171. var normals = [];
  28172. var uvs = [];
  28173. var colors = [];
  28174. var angle_step = Math.PI * 2 * arc / tessellation;
  28175. var angle;
  28176. var h;
  28177. var radius;
  28178. var tan = (diameterBottom - diameterTop) / 2 / height;
  28179. var ringVertex = BABYLON.Vector3.Zero();
  28180. var ringNormal = BABYLON.Vector3.Zero();
  28181. var ringFirstVertex = BABYLON.Vector3.Zero();
  28182. var ringFirstNormal = BABYLON.Vector3.Zero();
  28183. var quadNormal = BABYLON.Vector3.Zero();
  28184. var Y = BABYLON.Axis.Y;
  28185. // positions, normals, uvs
  28186. var i;
  28187. var j;
  28188. var r;
  28189. var ringIdx = 1;
  28190. var s = 1; // surface index
  28191. var cs = 0;
  28192. var v = 0;
  28193. for (i = 0; i <= subdivisions; i++) {
  28194. h = i / subdivisions;
  28195. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28196. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28197. for (r = 0; r < ringIdx; r++) {
  28198. if (hasRings) {
  28199. s += r;
  28200. }
  28201. if (enclose) {
  28202. s += 2 * r;
  28203. }
  28204. for (j = 0; j <= tessellation; j++) {
  28205. angle = j * angle_step;
  28206. // position
  28207. ringVertex.x = Math.cos(-angle) * radius;
  28208. ringVertex.y = -height / 2 + h * height;
  28209. ringVertex.z = Math.sin(-angle) * radius;
  28210. // normal
  28211. if (diameterTop === 0 && i === subdivisions) {
  28212. // if no top cap, reuse former normals
  28213. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28214. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28215. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28216. }
  28217. else {
  28218. ringNormal.x = ringVertex.x;
  28219. ringNormal.z = ringVertex.z;
  28220. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28221. ringNormal.normalize();
  28222. }
  28223. // keep first ring vertex values for enclose
  28224. if (j === 0) {
  28225. ringFirstVertex.copyFrom(ringVertex);
  28226. ringFirstNormal.copyFrom(ringNormal);
  28227. }
  28228. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28229. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28230. if (hasRings) {
  28231. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28232. }
  28233. else {
  28234. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28235. }
  28236. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28237. if (faceColors) {
  28238. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28239. }
  28240. }
  28241. // if enclose, add four vertices and their dedicated normals
  28242. if (arc !== 1 && enclose) {
  28243. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28244. positions.push(0, ringVertex.y, 0);
  28245. positions.push(0, ringVertex.y, 0);
  28246. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28247. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28248. quadNormal.normalize();
  28249. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28250. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28251. quadNormal.normalize();
  28252. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28253. if (hasRings) {
  28254. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28255. }
  28256. else {
  28257. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28258. }
  28259. uvs.push(faceUV[s + 1].x, v);
  28260. uvs.push(faceUV[s + 1].z, v);
  28261. if (hasRings) {
  28262. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28263. }
  28264. else {
  28265. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28266. }
  28267. uvs.push(faceUV[s + 2].x, v);
  28268. uvs.push(faceUV[s + 2].z, v);
  28269. if (faceColors) {
  28270. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28271. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28272. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28273. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28274. }
  28275. }
  28276. if (cs !== s) {
  28277. cs = s;
  28278. }
  28279. }
  28280. }
  28281. // indices
  28282. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28283. var s;
  28284. i = 0;
  28285. for (s = 0; s < subdivisions; s++) {
  28286. for (j = 0; j < tessellation; j++) {
  28287. var i0 = i * (e + 1) + j;
  28288. var i1 = (i + 1) * (e + 1) + j;
  28289. var i2 = i * (e + 1) + (j + 1);
  28290. var i3 = (i + 1) * (e + 1) + (j + 1);
  28291. indices.push(i0, i1, i2);
  28292. indices.push(i3, i2, i1);
  28293. }
  28294. if (arc !== 1 && enclose) {
  28295. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28296. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28297. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28298. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28299. }
  28300. i = (hasRings) ? (i + 2) : (i + 1);
  28301. }
  28302. // Caps
  28303. var createCylinderCap = function (isTop) {
  28304. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28305. if (radius === 0) {
  28306. return;
  28307. }
  28308. // Cap positions, normals & uvs
  28309. var angle;
  28310. var circleVector;
  28311. var i;
  28312. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28313. var c;
  28314. if (faceColors) {
  28315. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28316. }
  28317. // cap center
  28318. var vbase = positions.length / 3;
  28319. var offset = isTop ? height / 2 : -height / 2;
  28320. var center = new BABYLON.Vector3(0, offset, 0);
  28321. positions.push(center.x, center.y, center.z);
  28322. normals.push(0, isTop ? 1 : -1, 0);
  28323. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28324. if (faceColors) {
  28325. colors.push(c.r, c.g, c.b, c.a);
  28326. }
  28327. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28328. for (i = 0; i <= tessellation; i++) {
  28329. angle = Math.PI * 2 * i * arc / tessellation;
  28330. var cos = Math.cos(-angle);
  28331. var sin = Math.sin(-angle);
  28332. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28333. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28334. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28335. normals.push(0, isTop ? 1 : -1, 0);
  28336. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28337. if (faceColors) {
  28338. colors.push(c.r, c.g, c.b, c.a);
  28339. }
  28340. }
  28341. // Cap indices
  28342. for (i = 0; i < tessellation; i++) {
  28343. if (!isTop) {
  28344. indices.push(vbase);
  28345. indices.push(vbase + (i + 1));
  28346. indices.push(vbase + (i + 2));
  28347. }
  28348. else {
  28349. indices.push(vbase);
  28350. indices.push(vbase + (i + 2));
  28351. indices.push(vbase + (i + 1));
  28352. }
  28353. }
  28354. };
  28355. // add caps to geometry
  28356. createCylinderCap(false);
  28357. createCylinderCap(true);
  28358. // Sides
  28359. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28360. var vertexData = new VertexData();
  28361. vertexData.indices = indices;
  28362. vertexData.positions = positions;
  28363. vertexData.normals = normals;
  28364. vertexData.uvs = uvs;
  28365. if (faceColors) {
  28366. vertexData.colors = colors;
  28367. }
  28368. return vertexData;
  28369. };
  28370. VertexData.CreateTorus = function (options) {
  28371. var indices = [];
  28372. var positions = [];
  28373. var normals = [];
  28374. var uvs = [];
  28375. var diameter = options.diameter || 1;
  28376. var thickness = options.thickness || 0.5;
  28377. var tessellation = options.tessellation || 16;
  28378. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28379. var stride = tessellation + 1;
  28380. for (var i = 0; i <= tessellation; i++) {
  28381. var u = i / tessellation;
  28382. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28383. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28384. for (var j = 0; j <= tessellation; j++) {
  28385. var v = 1 - j / tessellation;
  28386. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28387. var dx = Math.cos(innerAngle);
  28388. var dy = Math.sin(innerAngle);
  28389. // Create a vertex.
  28390. var normal = new BABYLON.Vector3(dx, dy, 0);
  28391. var position = normal.scale(thickness / 2);
  28392. var textureCoordinate = new BABYLON.Vector2(u, v);
  28393. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28394. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28395. positions.push(position.x, position.y, position.z);
  28396. normals.push(normal.x, normal.y, normal.z);
  28397. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28398. // And create indices for two triangles.
  28399. var nextI = (i + 1) % stride;
  28400. var nextJ = (j + 1) % stride;
  28401. indices.push(i * stride + j);
  28402. indices.push(i * stride + nextJ);
  28403. indices.push(nextI * stride + j);
  28404. indices.push(i * stride + nextJ);
  28405. indices.push(nextI * stride + nextJ);
  28406. indices.push(nextI * stride + j);
  28407. }
  28408. }
  28409. // Sides
  28410. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28411. // Result
  28412. var vertexData = new VertexData();
  28413. vertexData.indices = indices;
  28414. vertexData.positions = positions;
  28415. vertexData.normals = normals;
  28416. vertexData.uvs = uvs;
  28417. return vertexData;
  28418. };
  28419. VertexData.CreateLineSystem = function (options) {
  28420. var indices = [];
  28421. var positions = [];
  28422. var lines = options.lines;
  28423. var idx = 0;
  28424. for (var l = 0; l < lines.length; l++) {
  28425. var points = lines[l];
  28426. for (var index = 0; index < points.length; index++) {
  28427. positions.push(points[index].x, points[index].y, points[index].z);
  28428. if (index > 0) {
  28429. indices.push(idx - 1);
  28430. indices.push(idx);
  28431. }
  28432. idx++;
  28433. }
  28434. }
  28435. var vertexData = new VertexData();
  28436. vertexData.indices = indices;
  28437. vertexData.positions = positions;
  28438. return vertexData;
  28439. };
  28440. VertexData.CreateDashedLines = function (options) {
  28441. var dashSize = options.dashSize || 3;
  28442. var gapSize = options.gapSize || 1;
  28443. var dashNb = options.dashNb || 200;
  28444. var points = options.points;
  28445. var positions = new Array();
  28446. var indices = new Array();
  28447. var curvect = BABYLON.Vector3.Zero();
  28448. var lg = 0;
  28449. var nb = 0;
  28450. var shft = 0;
  28451. var dashshft = 0;
  28452. var curshft = 0;
  28453. var idx = 0;
  28454. var i = 0;
  28455. for (i = 0; i < points.length - 1; i++) {
  28456. points[i + 1].subtractToRef(points[i], curvect);
  28457. lg += curvect.length();
  28458. }
  28459. shft = lg / dashNb;
  28460. dashshft = dashSize * shft / (dashSize + gapSize);
  28461. for (i = 0; i < points.length - 1; i++) {
  28462. points[i + 1].subtractToRef(points[i], curvect);
  28463. nb = Math.floor(curvect.length() / shft);
  28464. curvect.normalize();
  28465. for (var j = 0; j < nb; j++) {
  28466. curshft = shft * j;
  28467. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28468. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28469. indices.push(idx, idx + 1);
  28470. idx += 2;
  28471. }
  28472. }
  28473. // Result
  28474. var vertexData = new VertexData();
  28475. vertexData.positions = positions;
  28476. vertexData.indices = indices;
  28477. return vertexData;
  28478. };
  28479. VertexData.CreateGround = function (options) {
  28480. var indices = [];
  28481. var positions = [];
  28482. var normals = [];
  28483. var uvs = [];
  28484. var row, col;
  28485. var width = options.width || 1;
  28486. var height = options.height || 1;
  28487. var subdivisions = options.subdivisions || 1;
  28488. for (row = 0; row <= subdivisions; row++) {
  28489. for (col = 0; col <= subdivisions; col++) {
  28490. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28491. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28492. positions.push(position.x, position.y, position.z);
  28493. normals.push(normal.x, normal.y, normal.z);
  28494. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28495. }
  28496. }
  28497. for (row = 0; row < subdivisions; row++) {
  28498. for (col = 0; col < subdivisions; col++) {
  28499. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28500. indices.push(col + 1 + row * (subdivisions + 1));
  28501. indices.push(col + row * (subdivisions + 1));
  28502. indices.push(col + (row + 1) * (subdivisions + 1));
  28503. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28504. indices.push(col + row * (subdivisions + 1));
  28505. }
  28506. }
  28507. // Result
  28508. var vertexData = new VertexData();
  28509. vertexData.indices = indices;
  28510. vertexData.positions = positions;
  28511. vertexData.normals = normals;
  28512. vertexData.uvs = uvs;
  28513. return vertexData;
  28514. };
  28515. VertexData.CreateTiledGround = function (options) {
  28516. var xmin = options.xmin;
  28517. var zmin = options.zmin;
  28518. var xmax = options.xmax;
  28519. var zmax = options.zmax;
  28520. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28521. var precision = options.precision || { w: 1, h: 1 };
  28522. var indices = [];
  28523. var positions = [];
  28524. var normals = [];
  28525. var uvs = [];
  28526. var row, col, tileRow, tileCol;
  28527. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28528. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28529. precision.w = (precision.w < 1) ? 1 : precision.w;
  28530. precision.h = (precision.h < 1) ? 1 : precision.h;
  28531. var tileSize = {
  28532. 'w': (xmax - xmin) / subdivisions.w,
  28533. 'h': (zmax - zmin) / subdivisions.h
  28534. };
  28535. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28536. // Indices
  28537. var base = positions.length / 3;
  28538. var rowLength = precision.w + 1;
  28539. for (row = 0; row < precision.h; row++) {
  28540. for (col = 0; col < precision.w; col++) {
  28541. var square = [
  28542. base + col + row * rowLength,
  28543. base + (col + 1) + row * rowLength,
  28544. base + (col + 1) + (row + 1) * rowLength,
  28545. base + col + (row + 1) * rowLength
  28546. ];
  28547. indices.push(square[1]);
  28548. indices.push(square[2]);
  28549. indices.push(square[3]);
  28550. indices.push(square[0]);
  28551. indices.push(square[1]);
  28552. indices.push(square[3]);
  28553. }
  28554. }
  28555. // Position, normals and uvs
  28556. var position = BABYLON.Vector3.Zero();
  28557. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28558. for (row = 0; row <= precision.h; row++) {
  28559. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28560. for (col = 0; col <= precision.w; col++) {
  28561. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28562. position.y = 0;
  28563. positions.push(position.x, position.y, position.z);
  28564. normals.push(normal.x, normal.y, normal.z);
  28565. uvs.push(col / precision.w, row / precision.h);
  28566. }
  28567. }
  28568. }
  28569. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28570. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28571. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28572. }
  28573. }
  28574. // Result
  28575. var vertexData = new VertexData();
  28576. vertexData.indices = indices;
  28577. vertexData.positions = positions;
  28578. vertexData.normals = normals;
  28579. vertexData.uvs = uvs;
  28580. return vertexData;
  28581. };
  28582. VertexData.CreateGroundFromHeightMap = function (options) {
  28583. var indices = [];
  28584. var positions = [];
  28585. var normals = [];
  28586. var uvs = [];
  28587. var row, col;
  28588. // Vertices
  28589. for (row = 0; row <= options.subdivisions; row++) {
  28590. for (col = 0; col <= options.subdivisions; col++) {
  28591. 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));
  28592. // Compute height
  28593. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28594. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28595. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28596. var r = options.buffer[pos] / 255.0;
  28597. var g = options.buffer[pos + 1] / 255.0;
  28598. var b = options.buffer[pos + 2] / 255.0;
  28599. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28600. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28601. // Add vertex
  28602. positions.push(position.x, position.y, position.z);
  28603. normals.push(0, 0, 0);
  28604. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28605. }
  28606. }
  28607. // Indices
  28608. for (row = 0; row < options.subdivisions; row++) {
  28609. for (col = 0; col < options.subdivisions; col++) {
  28610. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28611. indices.push(col + 1 + row * (options.subdivisions + 1));
  28612. indices.push(col + row * (options.subdivisions + 1));
  28613. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28614. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28615. indices.push(col + row * (options.subdivisions + 1));
  28616. }
  28617. }
  28618. // Normals
  28619. VertexData.ComputeNormals(positions, indices, normals);
  28620. // Result
  28621. var vertexData = new VertexData();
  28622. vertexData.indices = indices;
  28623. vertexData.positions = positions;
  28624. vertexData.normals = normals;
  28625. vertexData.uvs = uvs;
  28626. return vertexData;
  28627. };
  28628. VertexData.CreatePlane = function (options) {
  28629. var indices = [];
  28630. var positions = [];
  28631. var normals = [];
  28632. var uvs = [];
  28633. var width = options.width || options.size || 1;
  28634. var height = options.height || options.size || 1;
  28635. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28636. // Vertices
  28637. var halfWidth = width / 2.0;
  28638. var halfHeight = height / 2.0;
  28639. positions.push(-halfWidth, -halfHeight, 0);
  28640. normals.push(0, 0, -1.0);
  28641. uvs.push(0.0, 0.0);
  28642. positions.push(halfWidth, -halfHeight, 0);
  28643. normals.push(0, 0, -1.0);
  28644. uvs.push(1.0, 0.0);
  28645. positions.push(halfWidth, halfHeight, 0);
  28646. normals.push(0, 0, -1.0);
  28647. uvs.push(1.0, 1.0);
  28648. positions.push(-halfWidth, halfHeight, 0);
  28649. normals.push(0, 0, -1.0);
  28650. uvs.push(0.0, 1.0);
  28651. // Indices
  28652. indices.push(0);
  28653. indices.push(1);
  28654. indices.push(2);
  28655. indices.push(0);
  28656. indices.push(2);
  28657. indices.push(3);
  28658. // Sides
  28659. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28660. // Result
  28661. var vertexData = new VertexData();
  28662. vertexData.indices = indices;
  28663. vertexData.positions = positions;
  28664. vertexData.normals = normals;
  28665. vertexData.uvs = uvs;
  28666. return vertexData;
  28667. };
  28668. VertexData.CreateDisc = function (options) {
  28669. var positions = [];
  28670. var indices = [];
  28671. var normals = [];
  28672. var uvs = [];
  28673. var radius = options.radius || 0.5;
  28674. var tessellation = options.tessellation || 64;
  28675. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28677. // positions and uvs
  28678. positions.push(0, 0, 0); // disc center first
  28679. uvs.push(0.5, 0.5);
  28680. var theta = Math.PI * 2 * arc;
  28681. var step = theta / tessellation;
  28682. for (var a = 0; a < theta; a += step) {
  28683. var x = Math.cos(a);
  28684. var y = Math.sin(a);
  28685. var u = (x + 1) / 2;
  28686. var v = (1 - y) / 2;
  28687. positions.push(radius * x, radius * y, 0);
  28688. uvs.push(u, v);
  28689. }
  28690. if (arc === 1) {
  28691. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28692. uvs.push(uvs[2], uvs[3]);
  28693. }
  28694. //indices
  28695. var vertexNb = positions.length / 3;
  28696. for (var i = 1; i < vertexNb - 1; i++) {
  28697. indices.push(i + 1, 0, i);
  28698. }
  28699. // result
  28700. VertexData.ComputeNormals(positions, indices, normals);
  28701. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28702. var vertexData = new VertexData();
  28703. vertexData.indices = indices;
  28704. vertexData.positions = positions;
  28705. vertexData.normals = normals;
  28706. vertexData.uvs = uvs;
  28707. return vertexData;
  28708. };
  28709. VertexData.CreateIcoSphere = function (options) {
  28710. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28711. var radius = options.radius || 1;
  28712. var flat = (options.flat === undefined) ? true : options.flat;
  28713. var subdivisions = options.subdivisions || 4;
  28714. var radiusX = options.radiusX || radius;
  28715. var radiusY = options.radiusY || radius;
  28716. var radiusZ = options.radiusZ || radius;
  28717. var t = (1 + Math.sqrt(5)) / 2;
  28718. // 12 vertex x,y,z
  28719. var ico_vertices = [
  28720. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28721. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28722. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28723. ];
  28724. // index of 3 vertex makes a face of icopshere
  28725. var ico_indices = [
  28726. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28727. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28728. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28729. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28730. ];
  28731. // vertex for uv have aliased position, not for UV
  28732. var vertices_unalias_id = [
  28733. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28734. // vertex alias
  28735. 0,
  28736. 2,
  28737. 3,
  28738. 3,
  28739. 3,
  28740. 4,
  28741. 7,
  28742. 8,
  28743. 9,
  28744. 9,
  28745. 10,
  28746. 11 // 23: B + 12
  28747. ];
  28748. // uv as integer step (not pixels !)
  28749. var ico_vertexuv = [
  28750. 5, 1, 3, 1, 6, 4, 0, 0,
  28751. 5, 3, 4, 2, 2, 2, 4, 0,
  28752. 2, 0, 1, 1, 6, 0, 6, 2,
  28753. // vertex alias (for same vertex on different faces)
  28754. 0, 4,
  28755. 3, 3,
  28756. 4, 4,
  28757. 3, 1,
  28758. 4, 2,
  28759. 4, 4,
  28760. 0, 2,
  28761. 1, 1,
  28762. 2, 2,
  28763. 3, 3,
  28764. 1, 3,
  28765. 2, 4 // 23: B + 12
  28766. ];
  28767. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28768. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28769. // First island of uv mapping
  28770. // v = 4h 3+ 2
  28771. // v = 3h 9+ 4
  28772. // v = 2h 9+ 5 B
  28773. // v = 1h 9 1 0
  28774. // v = 0h 3 8 7 A
  28775. // u = 0 1 2 3 4 5 6 *a
  28776. // Second island of uv mapping
  28777. // v = 4h 0+ B+ 4+
  28778. // v = 3h A+ 2+
  28779. // v = 2h 7+ 6 3+
  28780. // v = 1h 8+ 3+
  28781. // v = 0h
  28782. // u = 0 1 2 3 4 5 6 *a
  28783. // Face layout on texture UV mapping
  28784. // ============
  28785. // \ 4 /\ 16 / ======
  28786. // \ / \ / /\ 11 /
  28787. // \/ 7 \/ / \ /
  28788. // ======= / 10 \/
  28789. // /\ 17 /\ =======
  28790. // / \ / \ \ 15 /\
  28791. // / 8 \/ 12 \ \ / \
  28792. // ============ \/ 6 \
  28793. // \ 18 /\ ============
  28794. // \ / \ \ 5 /\ 0 /
  28795. // \/ 13 \ \ / \ /
  28796. // ======= \/ 1 \/
  28797. // =============
  28798. // /\ 19 /\ 2 /\
  28799. // / \ / \ / \
  28800. // / 14 \/ 9 \/ 3 \
  28801. // ===================
  28802. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28803. var ustep = 138 / 1024;
  28804. var vstep = 239 / 1024;
  28805. var uoffset = 60 / 1024;
  28806. var voffset = 26 / 1024;
  28807. // Second island should have margin, not to touch the first island
  28808. // avoid any borderline artefact in pixel rounding
  28809. var island_u_offset = -40 / 1024;
  28810. var island_v_offset = +20 / 1024;
  28811. // face is either island 0 or 1 :
  28812. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28813. var island = [
  28814. 0, 0, 0, 0, 1,
  28815. 0, 0, 1, 1, 0,
  28816. 0, 0, 1, 1, 0,
  28817. 0, 1, 1, 1, 0 // 15 - 19
  28818. ];
  28819. var indices = [];
  28820. var positions = [];
  28821. var normals = [];
  28822. var uvs = [];
  28823. var current_indice = 0;
  28824. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28825. var face_vertex_pos = new Array(3);
  28826. var face_vertex_uv = new Array(3);
  28827. var v012;
  28828. for (v012 = 0; v012 < 3; v012++) {
  28829. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28830. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28831. }
  28832. // create all with normals
  28833. for (var face = 0; face < 20; face++) {
  28834. // 3 vertex per face
  28835. for (v012 = 0; v012 < 3; v012++) {
  28836. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28837. var v_id = ico_indices[3 * face + v012];
  28838. // vertex have 3D position (x,y,z)
  28839. 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]);
  28840. // Normalize to get normal, then scale to radius
  28841. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28842. // uv Coordinates from vertex ID
  28843. 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);
  28844. }
  28845. // Subdivide the face (interpolate pos, norm, uv)
  28846. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28847. // - norm is linear interpolation of vertex corner normal
  28848. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28849. // - uv is linear interpolation
  28850. //
  28851. // Topology is as below for sub-divide by 2
  28852. // vertex shown as v0,v1,v2
  28853. // interp index is i1 to progress in range [v0,v1[
  28854. // interp index is i2 to progress in range [v0,v2[
  28855. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28856. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28857. //
  28858. //
  28859. // i2 v2
  28860. // ^ ^
  28861. // / / \
  28862. // / / \
  28863. // / / \
  28864. // / / (0,1) \
  28865. // / #---------\
  28866. // / / \ (0,0)'/ \
  28867. // / / \ / \
  28868. // / / \ / \
  28869. // / / (0,0) \ / (1,0) \
  28870. // / #---------#---------\
  28871. // v0 v1
  28872. //
  28873. // --------------------> i1
  28874. //
  28875. // interp of (i1,i2):
  28876. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28877. // along i1 : lerp(x0,x1, i1/(S-i2))
  28878. //
  28879. // centroid of triangle is needed to get help normal computation
  28880. // (c1,c2) are used for centroid location
  28881. var interp_vertex = function (i1, i2, c1, c2) {
  28882. // vertex is interpolated from
  28883. // - face_vertex_pos[0..2]
  28884. // - face_vertex_uv[0..2]
  28885. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28886. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28887. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28888. pos_interp.normalize();
  28889. var vertex_normal;
  28890. if (flat) {
  28891. // in flat mode, recalculate normal as face centroid normal
  28892. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28893. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28894. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28895. }
  28896. else {
  28897. // in smooth mode, recalculate normal from each single vertex position
  28898. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28899. }
  28900. // Vertex normal need correction due to X,Y,Z radius scaling
  28901. vertex_normal.x /= radiusX;
  28902. vertex_normal.y /= radiusY;
  28903. vertex_normal.z /= radiusZ;
  28904. vertex_normal.normalize();
  28905. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28906. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28907. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28908. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28909. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28910. uvs.push(uv_interp.x, uv_interp.y);
  28911. // push each vertex has member of a face
  28912. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28913. indices.push(current_indice);
  28914. current_indice++;
  28915. };
  28916. for (var i2 = 0; i2 < subdivisions; i2++) {
  28917. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28918. // face : (i1,i2) for /\ :
  28919. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28920. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28921. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28922. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28923. if (i1 + i2 + 1 < subdivisions) {
  28924. // face : (i1,i2)' for \/ :
  28925. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28926. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28927. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28928. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28929. }
  28930. }
  28931. }
  28932. }
  28933. // Sides
  28934. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28935. // Result
  28936. var vertexData = new VertexData();
  28937. vertexData.indices = indices;
  28938. vertexData.positions = positions;
  28939. vertexData.normals = normals;
  28940. vertexData.uvs = uvs;
  28941. return vertexData;
  28942. };
  28943. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28944. VertexData.CreatePolyhedron = function (options) {
  28945. // provided polyhedron types :
  28946. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28947. // 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)
  28948. var polyhedra = [];
  28949. 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]] };
  28950. 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]] };
  28951. polyhedra[2] = {
  28952. 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]],
  28953. 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]]
  28954. };
  28955. polyhedra[3] = {
  28956. 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]],
  28957. 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]]
  28958. };
  28959. polyhedra[4] = {
  28960. 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]],
  28961. 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]]
  28962. };
  28963. 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]] };
  28964. 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]] };
  28965. 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]] };
  28966. 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]] };
  28967. 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]] };
  28968. 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]] };
  28969. 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]] };
  28970. 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]] };
  28971. 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]] };
  28972. polyhedra[14] = {
  28973. 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]],
  28974. 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]]
  28975. };
  28976. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28977. var size = options.size;
  28978. var sizeX = options.sizeX || size || 1;
  28979. var sizeY = options.sizeY || size || 1;
  28980. var sizeZ = options.sizeZ || size || 1;
  28981. var data = options.custom || polyhedra[type];
  28982. var nbfaces = data.face.length;
  28983. var faceUV = options.faceUV || new Array(nbfaces);
  28984. var faceColors = options.faceColors;
  28985. var flat = (options.flat === undefined) ? true : options.flat;
  28986. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28987. var positions = [];
  28988. var indices = [];
  28989. var normals = [];
  28990. var uvs = [];
  28991. var colors = [];
  28992. var index = 0;
  28993. var faceIdx = 0; // face cursor in the array "indexes"
  28994. var indexes = [];
  28995. var i = 0;
  28996. var f = 0;
  28997. var u, v, ang, x, y, tmp;
  28998. // default face colors and UV if undefined
  28999. if (flat) {
  29000. for (f = 0; f < nbfaces; f++) {
  29001. if (faceColors && faceColors[f] === undefined) {
  29002. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29003. }
  29004. if (faceUV && faceUV[f] === undefined) {
  29005. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29006. }
  29007. }
  29008. }
  29009. if (!flat) {
  29010. for (i = 0; i < data.vertex.length; i++) {
  29011. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29012. uvs.push(0, 0);
  29013. }
  29014. for (f = 0; f < nbfaces; f++) {
  29015. for (i = 0; i < data.face[f].length - 2; i++) {
  29016. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29017. }
  29018. }
  29019. }
  29020. else {
  29021. for (f = 0; f < nbfaces; f++) {
  29022. var fl = data.face[f].length; // number of vertices of the current face
  29023. ang = 2 * Math.PI / fl;
  29024. x = 0.5 * Math.tan(ang / 2);
  29025. y = 0.5;
  29026. // positions, uvs, colors
  29027. for (i = 0; i < fl; i++) {
  29028. // positions
  29029. 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);
  29030. indexes.push(index);
  29031. index++;
  29032. // uvs
  29033. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29034. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29035. uvs.push(u, v);
  29036. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29037. y = x * Math.sin(ang) + y * Math.cos(ang);
  29038. x = tmp;
  29039. // colors
  29040. if (faceColors) {
  29041. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29042. }
  29043. }
  29044. // indices from indexes
  29045. for (i = 0; i < fl - 2; i++) {
  29046. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29047. }
  29048. faceIdx += fl;
  29049. }
  29050. }
  29051. VertexData.ComputeNormals(positions, indices, normals);
  29052. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29053. var vertexData = new VertexData();
  29054. vertexData.positions = positions;
  29055. vertexData.indices = indices;
  29056. vertexData.normals = normals;
  29057. vertexData.uvs = uvs;
  29058. if (faceColors && flat) {
  29059. vertexData.colors = colors;
  29060. }
  29061. return vertexData;
  29062. };
  29063. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29064. VertexData.CreateTorusKnot = function (options) {
  29065. var indices = [];
  29066. var positions = [];
  29067. var normals = [];
  29068. var uvs = [];
  29069. var radius = options.radius || 2;
  29070. var tube = options.tube || 0.5;
  29071. var radialSegments = options.radialSegments || 32;
  29072. var tubularSegments = options.tubularSegments || 32;
  29073. var p = options.p || 2;
  29074. var q = options.q || 3;
  29075. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29076. // Helper
  29077. var getPos = function (angle) {
  29078. var cu = Math.cos(angle);
  29079. var su = Math.sin(angle);
  29080. var quOverP = q / p * angle;
  29081. var cs = Math.cos(quOverP);
  29082. var tx = radius * (2 + cs) * 0.5 * cu;
  29083. var ty = radius * (2 + cs) * su * 0.5;
  29084. var tz = radius * Math.sin(quOverP) * 0.5;
  29085. return new BABYLON.Vector3(tx, ty, tz);
  29086. };
  29087. // Vertices
  29088. var i;
  29089. var j;
  29090. for (i = 0; i <= radialSegments; i++) {
  29091. var modI = i % radialSegments;
  29092. var u = modI / radialSegments * 2 * p * Math.PI;
  29093. var p1 = getPos(u);
  29094. var p2 = getPos(u + 0.01);
  29095. var tang = p2.subtract(p1);
  29096. var n = p2.add(p1);
  29097. var bitan = BABYLON.Vector3.Cross(tang, n);
  29098. n = BABYLON.Vector3.Cross(bitan, tang);
  29099. bitan.normalize();
  29100. n.normalize();
  29101. for (j = 0; j < tubularSegments; j++) {
  29102. var modJ = j % tubularSegments;
  29103. var v = modJ / tubularSegments * 2 * Math.PI;
  29104. var cx = -tube * Math.cos(v);
  29105. var cy = tube * Math.sin(v);
  29106. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29107. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29108. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29109. uvs.push(i / radialSegments);
  29110. uvs.push(j / tubularSegments);
  29111. }
  29112. }
  29113. for (i = 0; i < radialSegments; i++) {
  29114. for (j = 0; j < tubularSegments; j++) {
  29115. var jNext = (j + 1) % tubularSegments;
  29116. var a = i * tubularSegments + j;
  29117. var b = (i + 1) * tubularSegments + j;
  29118. var c = (i + 1) * tubularSegments + jNext;
  29119. var d = i * tubularSegments + jNext;
  29120. indices.push(d);
  29121. indices.push(b);
  29122. indices.push(a);
  29123. indices.push(d);
  29124. indices.push(c);
  29125. indices.push(b);
  29126. }
  29127. }
  29128. // Normals
  29129. VertexData.ComputeNormals(positions, indices, normals);
  29130. // Sides
  29131. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29132. // Result
  29133. var vertexData = new VertexData();
  29134. vertexData.indices = indices;
  29135. vertexData.positions = positions;
  29136. vertexData.normals = normals;
  29137. vertexData.uvs = uvs;
  29138. return vertexData;
  29139. };
  29140. // Tools
  29141. /**
  29142. * @param {any} - positions (number[] or Float32Array)
  29143. * @param {any} - indices (number[] or Uint16Array)
  29144. * @param {any} - normals (number[] or Float32Array)
  29145. */
  29146. VertexData.ComputeNormals = function (positions, indices, normals) {
  29147. var index = 0;
  29148. var p1p2x = 0.0;
  29149. var p1p2y = 0.0;
  29150. var p1p2z = 0.0;
  29151. var p3p2x = 0.0;
  29152. var p3p2y = 0.0;
  29153. var p3p2z = 0.0;
  29154. var faceNormalx = 0.0;
  29155. var faceNormaly = 0.0;
  29156. var faceNormalz = 0.0;
  29157. var length = 0.0;
  29158. var i1 = 0;
  29159. var i2 = 0;
  29160. var i3 = 0;
  29161. for (index = 0; index < positions.length; index++) {
  29162. normals[index] = 0.0;
  29163. }
  29164. // indice triplet = 1 face
  29165. var nbFaces = indices.length / 3;
  29166. for (index = 0; index < nbFaces; index++) {
  29167. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29168. i2 = indices[index * 3 + 1];
  29169. i3 = indices[index * 3 + 2];
  29170. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29171. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29172. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29173. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29174. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29175. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29176. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29177. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29178. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29179. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29180. length = (length === 0) ? 1.0 : length;
  29181. faceNormalx /= length; // normalize this normal
  29182. faceNormaly /= length;
  29183. faceNormalz /= length;
  29184. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29185. normals[i1 * 3 + 1] += faceNormaly;
  29186. normals[i1 * 3 + 2] += faceNormalz;
  29187. normals[i2 * 3] += faceNormalx;
  29188. normals[i2 * 3 + 1] += faceNormaly;
  29189. normals[i2 * 3 + 2] += faceNormalz;
  29190. normals[i3 * 3] += faceNormalx;
  29191. normals[i3 * 3 + 1] += faceNormaly;
  29192. normals[i3 * 3 + 2] += faceNormalz;
  29193. }
  29194. // last normalization of each normal
  29195. for (index = 0; index < normals.length / 3; index++) {
  29196. faceNormalx = normals[index * 3];
  29197. faceNormaly = normals[index * 3 + 1];
  29198. faceNormalz = normals[index * 3 + 2];
  29199. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29200. length = (length === 0) ? 1.0 : length;
  29201. faceNormalx /= length;
  29202. faceNormaly /= length;
  29203. faceNormalz /= length;
  29204. normals[index * 3] = faceNormalx;
  29205. normals[index * 3 + 1] = faceNormaly;
  29206. normals[index * 3 + 2] = faceNormalz;
  29207. }
  29208. };
  29209. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29210. var li = indices.length;
  29211. var ln = normals.length;
  29212. var i;
  29213. var n;
  29214. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29215. switch (sideOrientation) {
  29216. case BABYLON.Mesh.FRONTSIDE:
  29217. // nothing changed
  29218. break;
  29219. case BABYLON.Mesh.BACKSIDE:
  29220. var tmp;
  29221. // indices
  29222. for (i = 0; i < li; i += 3) {
  29223. tmp = indices[i];
  29224. indices[i] = indices[i + 2];
  29225. indices[i + 2] = tmp;
  29226. }
  29227. // normals
  29228. for (n = 0; n < ln; n++) {
  29229. normals[n] = -normals[n];
  29230. }
  29231. break;
  29232. case BABYLON.Mesh.DOUBLESIDE:
  29233. // positions
  29234. var lp = positions.length;
  29235. var l = lp / 3;
  29236. for (var p = 0; p < lp; p++) {
  29237. positions[lp + p] = positions[p];
  29238. }
  29239. // indices
  29240. for (i = 0; i < li; i += 3) {
  29241. indices[i + li] = indices[i + 2] + l;
  29242. indices[i + 1 + li] = indices[i + 1] + l;
  29243. indices[i + 2 + li] = indices[i] + l;
  29244. }
  29245. // normals
  29246. for (n = 0; n < ln; n++) {
  29247. normals[ln + n] = -normals[n];
  29248. }
  29249. // uvs
  29250. var lu = uvs.length;
  29251. for (var u = 0; u < lu; u++) {
  29252. uvs[u + lu] = uvs[u];
  29253. }
  29254. break;
  29255. }
  29256. };
  29257. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29258. var vertexData = new VertexData();
  29259. // positions
  29260. var positions = parsedVertexData.positions;
  29261. if (positions) {
  29262. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29263. }
  29264. // normals
  29265. var normals = parsedVertexData.normals;
  29266. if (normals) {
  29267. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29268. }
  29269. // uvs
  29270. var uvs = parsedVertexData.uvs;
  29271. if (uvs) {
  29272. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29273. }
  29274. // uv2s
  29275. var uv2s = parsedVertexData.uv2s;
  29276. if (uv2s) {
  29277. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29278. }
  29279. // uv3s
  29280. var uv3s = parsedVertexData.uv3s;
  29281. if (uv3s) {
  29282. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29283. }
  29284. // uv4s
  29285. var uv4s = parsedVertexData.uv4s;
  29286. if (uv4s) {
  29287. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29288. }
  29289. // uv5s
  29290. var uv5s = parsedVertexData.uv5s;
  29291. if (uv5s) {
  29292. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29293. }
  29294. // uv6s
  29295. var uv6s = parsedVertexData.uv6s;
  29296. if (uv6s) {
  29297. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29298. }
  29299. // colors
  29300. var colors = parsedVertexData.colors;
  29301. if (colors) {
  29302. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29303. }
  29304. // matricesIndices
  29305. var matricesIndices = parsedVertexData.matricesIndices;
  29306. if (matricesIndices) {
  29307. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29308. }
  29309. // matricesWeights
  29310. var matricesWeights = parsedVertexData.matricesWeights;
  29311. if (matricesWeights) {
  29312. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29313. }
  29314. // indices
  29315. var indices = parsedVertexData.indices;
  29316. if (indices) {
  29317. vertexData.indices = indices;
  29318. }
  29319. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29320. };
  29321. return VertexData;
  29322. })();
  29323. BABYLON.VertexData = VertexData;
  29324. })(BABYLON || (BABYLON = {}));
  29325. var BABYLON;
  29326. (function (BABYLON) {
  29327. var Tags = (function () {
  29328. function Tags() {
  29329. }
  29330. Tags.EnableFor = function (obj) {
  29331. obj._tags = obj._tags || {};
  29332. obj.hasTags = function () {
  29333. return Tags.HasTags(obj);
  29334. };
  29335. obj.addTags = function (tagsString) {
  29336. return Tags.AddTagsTo(obj, tagsString);
  29337. };
  29338. obj.removeTags = function (tagsString) {
  29339. return Tags.RemoveTagsFrom(obj, tagsString);
  29340. };
  29341. obj.matchesTagsQuery = function (tagsQuery) {
  29342. return Tags.MatchesQuery(obj, tagsQuery);
  29343. };
  29344. };
  29345. Tags.DisableFor = function (obj) {
  29346. delete obj._tags;
  29347. delete obj.hasTags;
  29348. delete obj.addTags;
  29349. delete obj.removeTags;
  29350. delete obj.matchesTagsQuery;
  29351. };
  29352. Tags.HasTags = function (obj) {
  29353. if (!obj._tags) {
  29354. return false;
  29355. }
  29356. return !BABYLON.Tools.IsEmpty(obj._tags);
  29357. };
  29358. Tags.GetTags = function (obj, asString) {
  29359. if (asString === void 0) { asString = true; }
  29360. if (!obj._tags) {
  29361. return null;
  29362. }
  29363. if (asString) {
  29364. var tagsArray = [];
  29365. for (var tag in obj._tags) {
  29366. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29367. tagsArray.push(tag);
  29368. }
  29369. }
  29370. return tagsArray.join(" ");
  29371. }
  29372. else {
  29373. return obj._tags;
  29374. }
  29375. };
  29376. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29377. // a tag cannot start with '||', '&&', and '!'
  29378. // it cannot contain whitespaces
  29379. Tags.AddTagsTo = function (obj, tagsString) {
  29380. if (!tagsString) {
  29381. return;
  29382. }
  29383. if (typeof tagsString !== "string") {
  29384. return;
  29385. }
  29386. var tags = tagsString.split(" ");
  29387. for (var t in tags) {
  29388. Tags._AddTagTo(obj, tags[t]);
  29389. }
  29390. };
  29391. Tags._AddTagTo = function (obj, tag) {
  29392. tag = tag.trim();
  29393. if (tag === "" || tag === "true" || tag === "false") {
  29394. return;
  29395. }
  29396. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29397. return;
  29398. }
  29399. Tags.EnableFor(obj);
  29400. obj._tags[tag] = true;
  29401. };
  29402. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29403. if (!Tags.HasTags(obj)) {
  29404. return;
  29405. }
  29406. var tags = tagsString.split(" ");
  29407. for (var t in tags) {
  29408. Tags._RemoveTagFrom(obj, tags[t]);
  29409. }
  29410. };
  29411. Tags._RemoveTagFrom = function (obj, tag) {
  29412. delete obj._tags[tag];
  29413. };
  29414. Tags.MatchesQuery = function (obj, tagsQuery) {
  29415. if (tagsQuery === undefined) {
  29416. return true;
  29417. }
  29418. if (tagsQuery === "") {
  29419. return Tags.HasTags(obj);
  29420. }
  29421. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29422. };
  29423. return Tags;
  29424. })();
  29425. BABYLON.Tags = Tags;
  29426. })(BABYLON || (BABYLON = {}));
  29427. var BABYLON;
  29428. (function (BABYLON) {
  29429. var Internals;
  29430. (function (Internals) {
  29431. var AndOrNotEvaluator = (function () {
  29432. function AndOrNotEvaluator() {
  29433. }
  29434. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29435. if (!query.match(/\([^\(\)]*\)/g)) {
  29436. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29437. }
  29438. else {
  29439. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29440. // remove parenthesis
  29441. r = r.slice(1, r.length - 1);
  29442. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29443. });
  29444. }
  29445. if (query === "true") {
  29446. return true;
  29447. }
  29448. if (query === "false") {
  29449. return false;
  29450. }
  29451. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29452. };
  29453. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29454. evaluateCallback = evaluateCallback || (function (r) {
  29455. return r === "true" ? true : false;
  29456. });
  29457. var result;
  29458. var or = parenthesisContent.split("||");
  29459. for (var i in or) {
  29460. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29461. var and = ori.split("&&");
  29462. if (and.length > 1) {
  29463. for (var j = 0; j < and.length; ++j) {
  29464. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29465. if (andj !== "true" && andj !== "false") {
  29466. if (andj[0] === "!") {
  29467. result = !evaluateCallback(andj.substring(1));
  29468. }
  29469. else {
  29470. result = evaluateCallback(andj);
  29471. }
  29472. }
  29473. else {
  29474. result = andj === "true" ? true : false;
  29475. }
  29476. if (!result) {
  29477. ori = "false";
  29478. break;
  29479. }
  29480. }
  29481. }
  29482. if (result || ori === "true") {
  29483. result = true;
  29484. break;
  29485. }
  29486. // result equals false (or undefined)
  29487. if (ori !== "true" && ori !== "false") {
  29488. if (ori[0] === "!") {
  29489. result = !evaluateCallback(ori.substring(1));
  29490. }
  29491. else {
  29492. result = evaluateCallback(ori);
  29493. }
  29494. }
  29495. else {
  29496. result = ori === "true" ? true : false;
  29497. }
  29498. }
  29499. // the whole parenthesis scope is replaced by 'true' or 'false'
  29500. return result ? "true" : "false";
  29501. };
  29502. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29503. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29504. // remove whitespaces
  29505. r = r.replace(/[\s]/g, function () { return ""; });
  29506. return r.length % 2 ? "!" : "";
  29507. });
  29508. booleanString = booleanString.trim();
  29509. if (booleanString === "!true") {
  29510. booleanString = "false";
  29511. }
  29512. else if (booleanString === "!false") {
  29513. booleanString = "true";
  29514. }
  29515. return booleanString;
  29516. };
  29517. return AndOrNotEvaluator;
  29518. })();
  29519. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29520. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29521. })(BABYLON || (BABYLON = {}));
  29522. var BABYLON;
  29523. (function (BABYLON) {
  29524. var PostProcessRenderPass = (function () {
  29525. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29526. this._enabled = true;
  29527. this._refCount = 0;
  29528. this._name = name;
  29529. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29530. this.setRenderList(renderList);
  29531. this._renderTexture.onBeforeRender = beforeRender;
  29532. this._renderTexture.onAfterRender = afterRender;
  29533. this._scene = scene;
  29534. this._renderList = renderList;
  29535. }
  29536. // private
  29537. PostProcessRenderPass.prototype._incRefCount = function () {
  29538. if (this._refCount === 0) {
  29539. this._scene.customRenderTargets.push(this._renderTexture);
  29540. }
  29541. return ++this._refCount;
  29542. };
  29543. PostProcessRenderPass.prototype._decRefCount = function () {
  29544. this._refCount--;
  29545. if (this._refCount <= 0) {
  29546. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29547. }
  29548. return this._refCount;
  29549. };
  29550. PostProcessRenderPass.prototype._update = function () {
  29551. this.setRenderList(this._renderList);
  29552. };
  29553. // public
  29554. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29555. this._renderTexture.renderList = renderList;
  29556. };
  29557. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29558. return this._renderTexture;
  29559. };
  29560. return PostProcessRenderPass;
  29561. })();
  29562. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29563. })(BABYLON || (BABYLON = {}));
  29564. var BABYLON;
  29565. (function (BABYLON) {
  29566. var PostProcessRenderEffect = (function () {
  29567. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29568. this._engine = engine;
  29569. this._name = name;
  29570. this._singleInstance = singleInstance || true;
  29571. this._getPostProcess = getPostProcess;
  29572. this._cameras = [];
  29573. this._indicesForCamera = [];
  29574. this._postProcesses = {};
  29575. this._renderPasses = {};
  29576. this._renderEffectAsPasses = {};
  29577. }
  29578. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29579. get: function () {
  29580. for (var index in this._postProcesses) {
  29581. if (!this._postProcesses[index].isSupported) {
  29582. return false;
  29583. }
  29584. }
  29585. return true;
  29586. },
  29587. enumerable: true,
  29588. configurable: true
  29589. });
  29590. PostProcessRenderEffect.prototype._update = function () {
  29591. for (var renderPassName in this._renderPasses) {
  29592. this._renderPasses[renderPassName]._update();
  29593. }
  29594. };
  29595. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29596. this._renderPasses[renderPass._name] = renderPass;
  29597. this._linkParameters();
  29598. };
  29599. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29600. delete this._renderPasses[renderPass._name];
  29601. this._linkParameters();
  29602. };
  29603. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29604. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29605. this._linkParameters();
  29606. };
  29607. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29608. for (var renderPassName in this._renderPasses) {
  29609. if (renderPassName === passName) {
  29610. return this._renderPasses[passName];
  29611. }
  29612. }
  29613. };
  29614. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29615. this._renderPasses = {};
  29616. this._linkParameters();
  29617. };
  29618. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29619. var cameraKey;
  29620. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29621. for (var i = 0; i < _cam.length; i++) {
  29622. var camera = _cam[i];
  29623. var cameraName = camera.name;
  29624. if (this._singleInstance) {
  29625. cameraKey = 0;
  29626. }
  29627. else {
  29628. cameraKey = cameraName;
  29629. }
  29630. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29631. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29632. if (!this._indicesForCamera[cameraName]) {
  29633. this._indicesForCamera[cameraName] = [];
  29634. }
  29635. this._indicesForCamera[cameraName].push(index);
  29636. if (this._cameras.indexOf(camera) === -1) {
  29637. this._cameras[cameraName] = camera;
  29638. }
  29639. for (var passName in this._renderPasses) {
  29640. this._renderPasses[passName]._incRefCount();
  29641. }
  29642. }
  29643. this._linkParameters();
  29644. };
  29645. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29646. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29647. for (var i = 0; i < _cam.length; i++) {
  29648. var camera = _cam[i];
  29649. var cameraName = camera.name;
  29650. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29651. var index = this._cameras.indexOf(cameraName);
  29652. this._indicesForCamera.splice(index, 1);
  29653. this._cameras.splice(index, 1);
  29654. for (var passName in this._renderPasses) {
  29655. this._renderPasses[passName]._decRefCount();
  29656. }
  29657. }
  29658. };
  29659. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29660. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29661. for (var i = 0; i < _cam.length; i++) {
  29662. var camera = _cam[i];
  29663. var cameraName = camera.name;
  29664. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29665. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29666. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29667. }
  29668. }
  29669. for (var passName in this._renderPasses) {
  29670. this._renderPasses[passName]._incRefCount();
  29671. }
  29672. }
  29673. };
  29674. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29675. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29676. for (var i = 0; i < _cam.length; i++) {
  29677. var camera = _cam[i];
  29678. var cameraName = camera.Name;
  29679. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29680. for (var passName in this._renderPasses) {
  29681. this._renderPasses[passName]._decRefCount();
  29682. }
  29683. }
  29684. };
  29685. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29686. if (this._singleInstance) {
  29687. return this._postProcesses[0];
  29688. }
  29689. else {
  29690. return this._postProcesses[camera.name];
  29691. }
  29692. };
  29693. PostProcessRenderEffect.prototype._linkParameters = function () {
  29694. var _this = this;
  29695. for (var index in this._postProcesses) {
  29696. if (this.applyParameters) {
  29697. this.applyParameters(this._postProcesses[index]);
  29698. }
  29699. this._postProcesses[index].onBeforeRender = function (effect) {
  29700. _this._linkTextures(effect);
  29701. };
  29702. }
  29703. };
  29704. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29705. for (var renderPassName in this._renderPasses) {
  29706. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29707. }
  29708. for (var renderEffectName in this._renderEffectAsPasses) {
  29709. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29710. }
  29711. };
  29712. return PostProcessRenderEffect;
  29713. })();
  29714. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29715. })(BABYLON || (BABYLON = {}));
  29716. var BABYLON;
  29717. (function (BABYLON) {
  29718. var PostProcessRenderPipeline = (function () {
  29719. function PostProcessRenderPipeline(engine, name) {
  29720. this._engine = engine;
  29721. this._name = name;
  29722. this._renderEffects = {};
  29723. this._renderEffectsForIsolatedPass = {};
  29724. this._cameras = [];
  29725. }
  29726. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29727. get: function () {
  29728. for (var renderEffectName in this._renderEffects) {
  29729. if (!this._renderEffects[renderEffectName].isSupported) {
  29730. return false;
  29731. }
  29732. }
  29733. return true;
  29734. },
  29735. enumerable: true,
  29736. configurable: true
  29737. });
  29738. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29739. this._renderEffects[renderEffect._name] = renderEffect;
  29740. };
  29741. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29742. var renderEffects = this._renderEffects[renderEffectName];
  29743. if (!renderEffects) {
  29744. return;
  29745. }
  29746. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29747. };
  29748. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29749. var renderEffects = this._renderEffects[renderEffectName];
  29750. if (!renderEffects) {
  29751. return;
  29752. }
  29753. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29754. };
  29755. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29756. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29757. var indicesToDelete = [];
  29758. var i;
  29759. for (i = 0; i < _cam.length; i++) {
  29760. var camera = _cam[i];
  29761. var cameraName = camera.name;
  29762. if (this._cameras.indexOf(camera) === -1) {
  29763. this._cameras[cameraName] = camera;
  29764. }
  29765. else if (unique) {
  29766. indicesToDelete.push(i);
  29767. }
  29768. }
  29769. for (i = 0; i < indicesToDelete.length; i++) {
  29770. cameras.splice(indicesToDelete[i], 1);
  29771. }
  29772. for (var renderEffectName in this._renderEffects) {
  29773. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29774. }
  29775. };
  29776. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  29777. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29778. for (var renderEffectName in this._renderEffects) {
  29779. this._renderEffects[renderEffectName]._detachCameras(_cam);
  29780. }
  29781. for (var i = 0; i < _cam.length; i++) {
  29782. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  29783. }
  29784. };
  29785. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  29786. var _this = this;
  29787. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29788. var pass = null;
  29789. var renderEffectName;
  29790. for (renderEffectName in this._renderEffects) {
  29791. pass = this._renderEffects[renderEffectName].getPass(passName);
  29792. if (pass != null) {
  29793. break;
  29794. }
  29795. }
  29796. if (pass === null) {
  29797. return;
  29798. }
  29799. for (renderEffectName in this._renderEffects) {
  29800. this._renderEffects[renderEffectName]._disable(_cam);
  29801. }
  29802. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  29803. for (var i = 0; i < _cam.length; i++) {
  29804. var camera = _cam[i];
  29805. var cameraName = camera.name;
  29806. 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); });
  29807. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  29808. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  29809. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  29810. }
  29811. };
  29812. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  29813. var _this = this;
  29814. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29815. for (var i = 0; i < _cam.length; i++) {
  29816. var camera = _cam[i];
  29817. var cameraName = camera.name;
  29818. 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); });
  29819. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  29820. }
  29821. for (var renderEffectName in this._renderEffects) {
  29822. this._renderEffects[renderEffectName]._enable(_cam);
  29823. }
  29824. };
  29825. PostProcessRenderPipeline.prototype._update = function () {
  29826. for (var renderEffectName in this._renderEffects) {
  29827. this._renderEffects[renderEffectName]._update();
  29828. }
  29829. for (var i = 0; i < this._cameras.length; i++) {
  29830. var cameraName = this._cameras[i].name;
  29831. if (this._renderEffectsForIsolatedPass[cameraName]) {
  29832. this._renderEffectsForIsolatedPass[cameraName]._update();
  29833. }
  29834. }
  29835. };
  29836. PostProcessRenderPipeline.prototype.dispose = function () {
  29837. // Must be implemented by children
  29838. };
  29839. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  29840. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  29841. return PostProcessRenderPipeline;
  29842. })();
  29843. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  29844. })(BABYLON || (BABYLON = {}));
  29845. var BABYLON;
  29846. (function (BABYLON) {
  29847. var PostProcessRenderPipelineManager = (function () {
  29848. function PostProcessRenderPipelineManager() {
  29849. this._renderPipelines = {};
  29850. }
  29851. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  29852. this._renderPipelines[renderPipeline._name] = renderPipeline;
  29853. };
  29854. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  29855. var renderPipeline = this._renderPipelines[renderPipelineName];
  29856. if (!renderPipeline) {
  29857. return;
  29858. }
  29859. renderPipeline._attachCameras(cameras, unique);
  29860. };
  29861. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  29862. var renderPipeline = this._renderPipelines[renderPipelineName];
  29863. if (!renderPipeline) {
  29864. return;
  29865. }
  29866. renderPipeline._detachCameras(cameras);
  29867. };
  29868. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29869. var renderPipeline = this._renderPipelines[renderPipelineName];
  29870. if (!renderPipeline) {
  29871. return;
  29872. }
  29873. renderPipeline._enableEffect(renderEffectName, cameras);
  29874. };
  29875. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29876. var renderPipeline = this._renderPipelines[renderPipelineName];
  29877. if (!renderPipeline) {
  29878. return;
  29879. }
  29880. renderPipeline._disableEffect(renderEffectName, cameras);
  29881. };
  29882. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  29883. var renderPipeline = this._renderPipelines[renderPipelineName];
  29884. if (!renderPipeline) {
  29885. return;
  29886. }
  29887. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  29888. };
  29889. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  29890. var renderPipeline = this._renderPipelines[renderPipelineName];
  29891. if (!renderPipeline) {
  29892. return;
  29893. }
  29894. renderPipeline._disableDisplayOnlyPass(cameras);
  29895. };
  29896. PostProcessRenderPipelineManager.prototype.update = function () {
  29897. for (var renderPipelineName in this._renderPipelines) {
  29898. var pipeline = this._renderPipelines[renderPipelineName];
  29899. if (!pipeline.isSupported) {
  29900. pipeline.dispose();
  29901. delete this._renderPipelines[renderPipelineName];
  29902. }
  29903. else {
  29904. pipeline._update();
  29905. }
  29906. }
  29907. };
  29908. return PostProcessRenderPipelineManager;
  29909. })();
  29910. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  29911. })(BABYLON || (BABYLON = {}));
  29912. var BABYLON;
  29913. (function (BABYLON) {
  29914. var BoundingBoxRenderer = (function () {
  29915. function BoundingBoxRenderer(scene) {
  29916. this.frontColor = new BABYLON.Color3(1, 1, 1);
  29917. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  29918. this.showBackLines = true;
  29919. this.renderList = new BABYLON.SmartArray(32);
  29920. this._scene = scene;
  29921. }
  29922. BoundingBoxRenderer.prototype._prepareRessources = function () {
  29923. if (this._colorShader) {
  29924. return;
  29925. }
  29926. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  29927. attributes: ["position"],
  29928. uniforms: ["worldViewProjection", "color"]
  29929. });
  29930. var engine = this._scene.getEngine();
  29931. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  29932. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  29933. 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]);
  29934. };
  29935. BoundingBoxRenderer.prototype.reset = function () {
  29936. this.renderList.reset();
  29937. };
  29938. BoundingBoxRenderer.prototype.render = function () {
  29939. if (this.renderList.length === 0) {
  29940. return;
  29941. }
  29942. this._prepareRessources();
  29943. if (!this._colorShader.isReady()) {
  29944. return;
  29945. }
  29946. var engine = this._scene.getEngine();
  29947. engine.setDepthWrite(false);
  29948. this._colorShader._preBind();
  29949. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  29950. var boundingBox = this.renderList.data[boundingBoxIndex];
  29951. var min = boundingBox.minimum;
  29952. var max = boundingBox.maximum;
  29953. var diff = max.subtract(min);
  29954. var median = min.add(diff.scale(0.5));
  29955. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  29956. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  29957. .multiply(boundingBox.getWorldMatrix());
  29958. // VBOs
  29959. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  29960. if (this.showBackLines) {
  29961. // Back
  29962. engine.setDepthFunctionToGreaterOrEqual();
  29963. this._scene.resetCachedMaterial();
  29964. this._colorShader.setColor4("color", this.backColor.toColor4());
  29965. this._colorShader.bind(worldMatrix);
  29966. // Draw order
  29967. engine.draw(false, 0, 24);
  29968. }
  29969. // Front
  29970. engine.setDepthFunctionToLess();
  29971. this._scene.resetCachedMaterial();
  29972. this._colorShader.setColor4("color", this.frontColor.toColor4());
  29973. this._colorShader.bind(worldMatrix);
  29974. // Draw order
  29975. engine.draw(false, 0, 24);
  29976. }
  29977. this._colorShader.unbind();
  29978. engine.setDepthFunctionToLessOrEqual();
  29979. engine.setDepthWrite(true);
  29980. };
  29981. BoundingBoxRenderer.prototype.dispose = function () {
  29982. if (!this._colorShader) {
  29983. return;
  29984. }
  29985. this._colorShader.dispose();
  29986. this._vb.dispose();
  29987. this._scene.getEngine()._releaseBuffer(this._ib);
  29988. };
  29989. return BoundingBoxRenderer;
  29990. })();
  29991. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  29992. })(BABYLON || (BABYLON = {}));
  29993. var BABYLON;
  29994. (function (BABYLON) {
  29995. var Condition = (function () {
  29996. function Condition(actionManager) {
  29997. this._actionManager = actionManager;
  29998. }
  29999. Condition.prototype.isValid = function () {
  30000. return true;
  30001. };
  30002. Condition.prototype._getProperty = function (propertyPath) {
  30003. return this._actionManager._getProperty(propertyPath);
  30004. };
  30005. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  30006. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30007. };
  30008. return Condition;
  30009. })();
  30010. BABYLON.Condition = Condition;
  30011. var ValueCondition = (function (_super) {
  30012. __extends(ValueCondition, _super);
  30013. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  30014. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  30015. _super.call(this, actionManager);
  30016. this.propertyPath = propertyPath;
  30017. this.value = value;
  30018. this.operator = operator;
  30019. this._target = this._getEffectiveTarget(target, this.propertyPath);
  30020. this._property = this._getProperty(this.propertyPath);
  30021. }
  30022. Object.defineProperty(ValueCondition, "IsEqual", {
  30023. get: function () {
  30024. return ValueCondition._IsEqual;
  30025. },
  30026. enumerable: true,
  30027. configurable: true
  30028. });
  30029. Object.defineProperty(ValueCondition, "IsDifferent", {
  30030. get: function () {
  30031. return ValueCondition._IsDifferent;
  30032. },
  30033. enumerable: true,
  30034. configurable: true
  30035. });
  30036. Object.defineProperty(ValueCondition, "IsGreater", {
  30037. get: function () {
  30038. return ValueCondition._IsGreater;
  30039. },
  30040. enumerable: true,
  30041. configurable: true
  30042. });
  30043. Object.defineProperty(ValueCondition, "IsLesser", {
  30044. get: function () {
  30045. return ValueCondition._IsLesser;
  30046. },
  30047. enumerable: true,
  30048. configurable: true
  30049. });
  30050. // Methods
  30051. ValueCondition.prototype.isValid = function () {
  30052. switch (this.operator) {
  30053. case ValueCondition.IsGreater:
  30054. return this._target[this._property] > this.value;
  30055. case ValueCondition.IsLesser:
  30056. return this._target[this._property] < this.value;
  30057. case ValueCondition.IsEqual:
  30058. case ValueCondition.IsDifferent:
  30059. var check;
  30060. if (this.value.equals) {
  30061. check = this.value.equals(this._target[this._property]);
  30062. }
  30063. else {
  30064. check = this.value === this._target[this._property];
  30065. }
  30066. return this.operator === ValueCondition.IsEqual ? check : !check;
  30067. }
  30068. return false;
  30069. };
  30070. // Statics
  30071. ValueCondition._IsEqual = 0;
  30072. ValueCondition._IsDifferent = 1;
  30073. ValueCondition._IsGreater = 2;
  30074. ValueCondition._IsLesser = 3;
  30075. return ValueCondition;
  30076. })(Condition);
  30077. BABYLON.ValueCondition = ValueCondition;
  30078. var PredicateCondition = (function (_super) {
  30079. __extends(PredicateCondition, _super);
  30080. function PredicateCondition(actionManager, predicate) {
  30081. _super.call(this, actionManager);
  30082. this.predicate = predicate;
  30083. }
  30084. PredicateCondition.prototype.isValid = function () {
  30085. return this.predicate();
  30086. };
  30087. return PredicateCondition;
  30088. })(Condition);
  30089. BABYLON.PredicateCondition = PredicateCondition;
  30090. var StateCondition = (function (_super) {
  30091. __extends(StateCondition, _super);
  30092. function StateCondition(actionManager, target, value) {
  30093. _super.call(this, actionManager);
  30094. this.value = value;
  30095. this._target = target;
  30096. }
  30097. // Methods
  30098. StateCondition.prototype.isValid = function () {
  30099. return this._target.state === this.value;
  30100. };
  30101. return StateCondition;
  30102. })(Condition);
  30103. BABYLON.StateCondition = StateCondition;
  30104. })(BABYLON || (BABYLON = {}));
  30105. var BABYLON;
  30106. (function (BABYLON) {
  30107. var Action = (function () {
  30108. function Action(triggerOptions, condition) {
  30109. this.triggerOptions = triggerOptions;
  30110. if (triggerOptions.parameter) {
  30111. this.trigger = triggerOptions.trigger;
  30112. this._triggerParameter = triggerOptions.parameter;
  30113. }
  30114. else {
  30115. this.trigger = triggerOptions;
  30116. }
  30117. this._nextActiveAction = this;
  30118. this._condition = condition;
  30119. }
  30120. // Methods
  30121. Action.prototype._prepare = function () {
  30122. };
  30123. Action.prototype.getTriggerParameter = function () {
  30124. return this._triggerParameter;
  30125. };
  30126. Action.prototype._executeCurrent = function (evt) {
  30127. if (this._nextActiveAction._condition) {
  30128. var condition = this._nextActiveAction._condition;
  30129. var currentRenderId = this._actionManager.getScene().getRenderId();
  30130. // We cache the current evaluation for the current frame
  30131. if (condition._evaluationId === currentRenderId) {
  30132. if (!condition._currentResult) {
  30133. return;
  30134. }
  30135. }
  30136. else {
  30137. condition._evaluationId = currentRenderId;
  30138. if (!condition.isValid()) {
  30139. condition._currentResult = false;
  30140. return;
  30141. }
  30142. condition._currentResult = true;
  30143. }
  30144. }
  30145. this._nextActiveAction.execute(evt);
  30146. this.skipToNextActiveAction();
  30147. };
  30148. Action.prototype.execute = function (evt) {
  30149. };
  30150. Action.prototype.skipToNextActiveAction = function () {
  30151. if (this._nextActiveAction._child) {
  30152. if (!this._nextActiveAction._child._actionManager) {
  30153. this._nextActiveAction._child._actionManager = this._actionManager;
  30154. }
  30155. this._nextActiveAction = this._nextActiveAction._child;
  30156. }
  30157. else {
  30158. this._nextActiveAction = this;
  30159. }
  30160. };
  30161. Action.prototype.then = function (action) {
  30162. this._child = action;
  30163. action._actionManager = this._actionManager;
  30164. action._prepare();
  30165. return action;
  30166. };
  30167. Action.prototype._getProperty = function (propertyPath) {
  30168. return this._actionManager._getProperty(propertyPath);
  30169. };
  30170. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30171. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30172. };
  30173. return Action;
  30174. })();
  30175. BABYLON.Action = Action;
  30176. })(BABYLON || (BABYLON = {}));
  30177. var BABYLON;
  30178. (function (BABYLON) {
  30179. /**
  30180. * ActionEvent is the event beint sent when an action is triggered.
  30181. */
  30182. var ActionEvent = (function () {
  30183. /**
  30184. * @constructor
  30185. * @param source The mesh or sprite that triggered the action.
  30186. * @param pointerX The X mouse cursor position at the time of the event
  30187. * @param pointerY The Y mouse cursor position at the time of the event
  30188. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30189. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30190. */
  30191. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30192. this.source = source;
  30193. this.pointerX = pointerX;
  30194. this.pointerY = pointerY;
  30195. this.meshUnderPointer = meshUnderPointer;
  30196. this.sourceEvent = sourceEvent;
  30197. this.additionalData = additionalData;
  30198. }
  30199. /**
  30200. * Helper function to auto-create an ActionEvent from a source mesh.
  30201. * @param source The source mesh that triggered the event
  30202. * @param evt {Event} The original (browser) event
  30203. */
  30204. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30205. var scene = source.getScene();
  30206. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30207. };
  30208. /**
  30209. * Helper function to auto-create an ActionEvent from a source mesh.
  30210. * @param source The source sprite that triggered the event
  30211. * @param scene Scene associated with the sprite
  30212. * @param evt {Event} The original (browser) event
  30213. */
  30214. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30215. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30216. };
  30217. /**
  30218. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30219. * @param scene the scene where the event occurred
  30220. * @param evt {Event} The original (browser) event
  30221. */
  30222. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30223. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30224. };
  30225. return ActionEvent;
  30226. })();
  30227. BABYLON.ActionEvent = ActionEvent;
  30228. /**
  30229. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30230. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30231. */
  30232. var ActionManager = (function () {
  30233. function ActionManager(scene) {
  30234. // Members
  30235. this.actions = new Array();
  30236. this._scene = scene;
  30237. scene._actionManagers.push(this);
  30238. }
  30239. Object.defineProperty(ActionManager, "NothingTrigger", {
  30240. get: function () {
  30241. return ActionManager._NothingTrigger;
  30242. },
  30243. enumerable: true,
  30244. configurable: true
  30245. });
  30246. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30247. get: function () {
  30248. return ActionManager._OnPickTrigger;
  30249. },
  30250. enumerable: true,
  30251. configurable: true
  30252. });
  30253. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30254. get: function () {
  30255. return ActionManager._OnLeftPickTrigger;
  30256. },
  30257. enumerable: true,
  30258. configurable: true
  30259. });
  30260. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30261. get: function () {
  30262. return ActionManager._OnRightPickTrigger;
  30263. },
  30264. enumerable: true,
  30265. configurable: true
  30266. });
  30267. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30268. get: function () {
  30269. return ActionManager._OnCenterPickTrigger;
  30270. },
  30271. enumerable: true,
  30272. configurable: true
  30273. });
  30274. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30275. get: function () {
  30276. return ActionManager._OnPickDownTrigger;
  30277. },
  30278. enumerable: true,
  30279. configurable: true
  30280. });
  30281. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30282. get: function () {
  30283. return ActionManager._OnPickUpTrigger;
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30289. /// This trigger will only be raised if you also declared a OnPickDown
  30290. get: function () {
  30291. return ActionManager._OnPickOutTrigger;
  30292. },
  30293. enumerable: true,
  30294. configurable: true
  30295. });
  30296. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30297. get: function () {
  30298. return ActionManager._OnLongPressTrigger;
  30299. },
  30300. enumerable: true,
  30301. configurable: true
  30302. });
  30303. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30304. get: function () {
  30305. return ActionManager._OnPointerOverTrigger;
  30306. },
  30307. enumerable: true,
  30308. configurable: true
  30309. });
  30310. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30311. get: function () {
  30312. return ActionManager._OnPointerOutTrigger;
  30313. },
  30314. enumerable: true,
  30315. configurable: true
  30316. });
  30317. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30318. get: function () {
  30319. return ActionManager._OnEveryFrameTrigger;
  30320. },
  30321. enumerable: true,
  30322. configurable: true
  30323. });
  30324. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30325. get: function () {
  30326. return ActionManager._OnIntersectionEnterTrigger;
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30332. get: function () {
  30333. return ActionManager._OnIntersectionExitTrigger;
  30334. },
  30335. enumerable: true,
  30336. configurable: true
  30337. });
  30338. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30339. get: function () {
  30340. return ActionManager._OnKeyDownTrigger;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30346. get: function () {
  30347. return ActionManager._OnKeyUpTrigger;
  30348. },
  30349. enumerable: true,
  30350. configurable: true
  30351. });
  30352. // Methods
  30353. ActionManager.prototype.dispose = function () {
  30354. var index = this._scene._actionManagers.indexOf(this);
  30355. if (index > -1) {
  30356. this._scene._actionManagers.splice(index, 1);
  30357. }
  30358. };
  30359. ActionManager.prototype.getScene = function () {
  30360. return this._scene;
  30361. };
  30362. /**
  30363. * Does this action manager handles actions of any of the given triggers
  30364. * @param {number[]} triggers - the triggers to be tested
  30365. * @return {boolean} whether one (or more) of the triggers is handeled
  30366. */
  30367. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30368. for (var index = 0; index < this.actions.length; index++) {
  30369. var action = this.actions[index];
  30370. if (triggers.indexOf(action.trigger) > -1) {
  30371. return true;
  30372. }
  30373. }
  30374. return false;
  30375. };
  30376. /**
  30377. * Does this action manager handles actions of a given trigger
  30378. * @param {number} trigger - the trigger to be tested
  30379. * @return {boolean} whether the trigger is handeled
  30380. */
  30381. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30382. for (var index = 0; index < this.actions.length; index++) {
  30383. var action = this.actions[index];
  30384. if (action.trigger === trigger) {
  30385. return true;
  30386. }
  30387. }
  30388. return false;
  30389. };
  30390. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30391. /**
  30392. * Does this action manager has pointer triggers
  30393. * @return {boolean} whether or not it has pointer triggers
  30394. */
  30395. get: function () {
  30396. for (var index = 0; index < this.actions.length; index++) {
  30397. var action = this.actions[index];
  30398. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30399. return true;
  30400. }
  30401. }
  30402. return false;
  30403. },
  30404. enumerable: true,
  30405. configurable: true
  30406. });
  30407. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30408. /**
  30409. * Does this action manager has pick triggers
  30410. * @return {boolean} whether or not it has pick triggers
  30411. */
  30412. get: function () {
  30413. for (var index = 0; index < this.actions.length; index++) {
  30414. var action = this.actions[index];
  30415. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30416. return true;
  30417. }
  30418. }
  30419. return false;
  30420. },
  30421. enumerable: true,
  30422. configurable: true
  30423. });
  30424. /**
  30425. * Registers an action to this action manager
  30426. * @param {BABYLON.Action} action - the action to be registered
  30427. * @return {BABYLON.Action} the action amended (prepared) after registration
  30428. */
  30429. ActionManager.prototype.registerAction = function (action) {
  30430. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30431. if (this.getScene().actionManager !== this) {
  30432. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30433. return null;
  30434. }
  30435. }
  30436. this.actions.push(action);
  30437. action._actionManager = this;
  30438. action._prepare();
  30439. return action;
  30440. };
  30441. /**
  30442. * Process a specific trigger
  30443. * @param {number} trigger - the trigger to process
  30444. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30445. */
  30446. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30447. for (var index = 0; index < this.actions.length; index++) {
  30448. var action = this.actions[index];
  30449. if (action.trigger === trigger) {
  30450. if (trigger === ActionManager.OnKeyUpTrigger
  30451. || trigger === ActionManager.OnKeyDownTrigger) {
  30452. var parameter = action.getTriggerParameter();
  30453. if (parameter) {
  30454. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30455. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30456. if (actualkey !== parameter.toLowerCase()) {
  30457. continue;
  30458. }
  30459. }
  30460. }
  30461. action._executeCurrent(evt);
  30462. }
  30463. }
  30464. };
  30465. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30466. var properties = propertyPath.split(".");
  30467. for (var index = 0; index < properties.length - 1; index++) {
  30468. target = target[properties[index]];
  30469. }
  30470. return target;
  30471. };
  30472. ActionManager.prototype._getProperty = function (propertyPath) {
  30473. var properties = propertyPath.split(".");
  30474. return properties[properties.length - 1];
  30475. };
  30476. ActionManager.Parse = function (parsedActions, object, scene) {
  30477. var actionManager = new BABYLON.ActionManager(scene);
  30478. if (object === null)
  30479. scene.actionManager = actionManager;
  30480. else
  30481. object.actionManager = actionManager;
  30482. // instanciate a new object
  30483. var instanciate = function (name, params) {
  30484. var newInstance = Object.create(BABYLON[name].prototype);
  30485. newInstance.constructor.apply(newInstance, params);
  30486. return newInstance;
  30487. };
  30488. var parseParameter = function (name, value, target, propertyPath) {
  30489. if (propertyPath === null) {
  30490. // String, boolean or float
  30491. var floatValue = parseFloat(value);
  30492. if (value === "true" || value === "false")
  30493. return value === "true";
  30494. else
  30495. return isNaN(floatValue) ? value : floatValue;
  30496. }
  30497. var effectiveTarget = propertyPath.split(".");
  30498. var values = value.split(",");
  30499. // Get effective Target
  30500. for (var i = 0; i < effectiveTarget.length; i++) {
  30501. target = target[effectiveTarget[i]];
  30502. }
  30503. // Return appropriate value with its type
  30504. if (typeof (target) === "boolean")
  30505. return values[0] === "true";
  30506. if (typeof (target) === "string")
  30507. return values[0];
  30508. // Parameters with multiple values such as Vector3 etc.
  30509. var split = new Array();
  30510. for (var i = 0; i < values.length; i++)
  30511. split.push(parseFloat(values[i]));
  30512. if (target instanceof BABYLON.Vector3)
  30513. return BABYLON.Vector3.FromArray(split);
  30514. if (target instanceof BABYLON.Vector4)
  30515. return BABYLON.Vector4.FromArray(split);
  30516. if (target instanceof BABYLON.Color3)
  30517. return BABYLON.Color3.FromArray(split);
  30518. if (target instanceof BABYLON.Color4)
  30519. return BABYLON.Color4.FromArray(split);
  30520. return parseFloat(values[0]);
  30521. };
  30522. // traverse graph per trigger
  30523. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30524. if (combineArray === void 0) { combineArray = null; }
  30525. if (parsedAction.detached)
  30526. return;
  30527. var parameters = new Array();
  30528. var target = null;
  30529. var propertyPath = null;
  30530. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30531. // Parameters
  30532. if (parsedAction.type === 2)
  30533. parameters.push(actionManager);
  30534. else
  30535. parameters.push(trigger);
  30536. if (combine) {
  30537. var actions = new Array();
  30538. for (var j = 0; j < parsedAction.combine.length; j++) {
  30539. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30540. }
  30541. parameters.push(actions);
  30542. }
  30543. else {
  30544. for (var i = 0; i < parsedAction.properties.length; i++) {
  30545. var value = parsedAction.properties[i].value;
  30546. var name = parsedAction.properties[i].name;
  30547. var targetType = parsedAction.properties[i].targetType;
  30548. if (name === "target")
  30549. if (targetType !== null && targetType === "SceneProperties")
  30550. value = target = scene;
  30551. else
  30552. value = target = scene.getNodeByName(value);
  30553. else if (name === "parent")
  30554. value = scene.getNodeByName(value);
  30555. else if (name === "sound")
  30556. value = scene.getSoundByName(value);
  30557. else if (name !== "propertyPath") {
  30558. if (parsedAction.type === 2 && name === "operator")
  30559. value = BABYLON.ValueCondition[value];
  30560. else
  30561. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30562. }
  30563. else {
  30564. propertyPath = value;
  30565. }
  30566. parameters.push(value);
  30567. }
  30568. }
  30569. if (combineArray === null) {
  30570. parameters.push(condition);
  30571. }
  30572. else {
  30573. parameters.push(null);
  30574. }
  30575. // If interpolate value action
  30576. if (parsedAction.name === "InterpolateValueAction") {
  30577. var param = parameters[parameters.length - 2];
  30578. parameters[parameters.length - 1] = param;
  30579. parameters[parameters.length - 2] = condition;
  30580. }
  30581. // Action or condition(s) and not CombineAction
  30582. var newAction = instanciate(parsedAction.name, parameters);
  30583. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30584. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30585. if (action)
  30586. action.then(nothing);
  30587. else
  30588. actionManager.registerAction(nothing);
  30589. action = nothing;
  30590. }
  30591. if (combineArray === null) {
  30592. if (newAction instanceof BABYLON.Condition) {
  30593. condition = newAction;
  30594. newAction = action;
  30595. }
  30596. else {
  30597. condition = null;
  30598. if (action)
  30599. action.then(newAction);
  30600. else
  30601. actionManager.registerAction(newAction);
  30602. }
  30603. }
  30604. else {
  30605. combineArray.push(newAction);
  30606. }
  30607. for (var i = 0; i < parsedAction.children.length; i++)
  30608. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30609. };
  30610. // triggers
  30611. for (var i = 0; i < parsedActions.children.length; i++) {
  30612. var triggerParams;
  30613. var trigger = parsedActions.children[i];
  30614. if (trigger.properties.length > 0) {
  30615. var param = trigger.properties[0].value;
  30616. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30617. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30618. }
  30619. else
  30620. triggerParams = BABYLON.ActionManager[trigger.name];
  30621. for (var j = 0; j < trigger.children.length; j++) {
  30622. if (!trigger.detached)
  30623. traverse(trigger.children[j], triggerParams, null, null);
  30624. }
  30625. }
  30626. };
  30627. // Statics
  30628. ActionManager._NothingTrigger = 0;
  30629. ActionManager._OnPickTrigger = 1;
  30630. ActionManager._OnLeftPickTrigger = 2;
  30631. ActionManager._OnRightPickTrigger = 3;
  30632. ActionManager._OnCenterPickTrigger = 4;
  30633. ActionManager._OnPickDownTrigger = 5;
  30634. ActionManager._OnPickUpTrigger = 6;
  30635. ActionManager._OnLongPressTrigger = 7;
  30636. ActionManager._OnPointerOverTrigger = 8;
  30637. ActionManager._OnPointerOutTrigger = 9;
  30638. ActionManager._OnEveryFrameTrigger = 10;
  30639. ActionManager._OnIntersectionEnterTrigger = 11;
  30640. ActionManager._OnIntersectionExitTrigger = 12;
  30641. ActionManager._OnKeyDownTrigger = 13;
  30642. ActionManager._OnKeyUpTrigger = 14;
  30643. ActionManager._OnPickOutTrigger = 15;
  30644. ActionManager.DragMovementThreshold = 10; // in pixels
  30645. ActionManager.LongPressDelay = 500; // in milliseconds
  30646. return ActionManager;
  30647. })();
  30648. BABYLON.ActionManager = ActionManager;
  30649. })(BABYLON || (BABYLON = {}));
  30650. var BABYLON;
  30651. (function (BABYLON) {
  30652. var InterpolateValueAction = (function (_super) {
  30653. __extends(InterpolateValueAction, _super);
  30654. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  30655. if (duration === void 0) { duration = 1000; }
  30656. _super.call(this, triggerOptions, condition);
  30657. this.propertyPath = propertyPath;
  30658. this.value = value;
  30659. this.duration = duration;
  30660. this.stopOtherAnimations = stopOtherAnimations;
  30661. this.onInterpolationDone = onInterpolationDone;
  30662. this._target = target;
  30663. }
  30664. InterpolateValueAction.prototype._prepare = function () {
  30665. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30666. this._property = this._getProperty(this.propertyPath);
  30667. };
  30668. InterpolateValueAction.prototype.execute = function () {
  30669. var scene = this._actionManager.getScene();
  30670. var keys = [
  30671. {
  30672. frame: 0,
  30673. value: this._target[this._property]
  30674. }, {
  30675. frame: 100,
  30676. value: this.value
  30677. }
  30678. ];
  30679. var dataType;
  30680. if (typeof this.value === "number") {
  30681. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  30682. }
  30683. else if (this.value instanceof BABYLON.Color3) {
  30684. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  30685. }
  30686. else if (this.value instanceof BABYLON.Vector3) {
  30687. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  30688. }
  30689. else if (this.value instanceof BABYLON.Matrix) {
  30690. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  30691. }
  30692. else if (this.value instanceof BABYLON.Quaternion) {
  30693. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  30694. }
  30695. else {
  30696. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  30697. return;
  30698. }
  30699. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30700. animation.setKeys(keys);
  30701. if (this.stopOtherAnimations) {
  30702. scene.stopAnimation(this._target);
  30703. }
  30704. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  30705. };
  30706. return InterpolateValueAction;
  30707. })(BABYLON.Action);
  30708. BABYLON.InterpolateValueAction = InterpolateValueAction;
  30709. })(BABYLON || (BABYLON = {}));
  30710. var BABYLON;
  30711. (function (BABYLON) {
  30712. var SwitchBooleanAction = (function (_super) {
  30713. __extends(SwitchBooleanAction, _super);
  30714. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  30715. _super.call(this, triggerOptions, condition);
  30716. this.propertyPath = propertyPath;
  30717. this._target = target;
  30718. }
  30719. SwitchBooleanAction.prototype._prepare = function () {
  30720. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30721. this._property = this._getProperty(this.propertyPath);
  30722. };
  30723. SwitchBooleanAction.prototype.execute = function () {
  30724. this._target[this._property] = !this._target[this._property];
  30725. };
  30726. return SwitchBooleanAction;
  30727. })(BABYLON.Action);
  30728. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  30729. var SetStateAction = (function (_super) {
  30730. __extends(SetStateAction, _super);
  30731. function SetStateAction(triggerOptions, target, value, condition) {
  30732. _super.call(this, triggerOptions, condition);
  30733. this.value = value;
  30734. this._target = target;
  30735. }
  30736. SetStateAction.prototype.execute = function () {
  30737. this._target.state = this.value;
  30738. };
  30739. return SetStateAction;
  30740. })(BABYLON.Action);
  30741. BABYLON.SetStateAction = SetStateAction;
  30742. var SetValueAction = (function (_super) {
  30743. __extends(SetValueAction, _super);
  30744. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  30745. _super.call(this, triggerOptions, condition);
  30746. this.propertyPath = propertyPath;
  30747. this.value = value;
  30748. this._target = target;
  30749. }
  30750. SetValueAction.prototype._prepare = function () {
  30751. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30752. this._property = this._getProperty(this.propertyPath);
  30753. };
  30754. SetValueAction.prototype.execute = function () {
  30755. this._target[this._property] = this.value;
  30756. };
  30757. return SetValueAction;
  30758. })(BABYLON.Action);
  30759. BABYLON.SetValueAction = SetValueAction;
  30760. var IncrementValueAction = (function (_super) {
  30761. __extends(IncrementValueAction, _super);
  30762. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  30763. _super.call(this, triggerOptions, condition);
  30764. this.propertyPath = propertyPath;
  30765. this.value = value;
  30766. this._target = target;
  30767. }
  30768. IncrementValueAction.prototype._prepare = function () {
  30769. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30770. this._property = this._getProperty(this.propertyPath);
  30771. if (typeof this._target[this._property] !== "number") {
  30772. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  30773. }
  30774. };
  30775. IncrementValueAction.prototype.execute = function () {
  30776. this._target[this._property] += this.value;
  30777. };
  30778. return IncrementValueAction;
  30779. })(BABYLON.Action);
  30780. BABYLON.IncrementValueAction = IncrementValueAction;
  30781. var PlayAnimationAction = (function (_super) {
  30782. __extends(PlayAnimationAction, _super);
  30783. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  30784. _super.call(this, triggerOptions, condition);
  30785. this.from = from;
  30786. this.to = to;
  30787. this.loop = loop;
  30788. this._target = target;
  30789. }
  30790. PlayAnimationAction.prototype._prepare = function () {
  30791. };
  30792. PlayAnimationAction.prototype.execute = function () {
  30793. var scene = this._actionManager.getScene();
  30794. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  30795. };
  30796. return PlayAnimationAction;
  30797. })(BABYLON.Action);
  30798. BABYLON.PlayAnimationAction = PlayAnimationAction;
  30799. var StopAnimationAction = (function (_super) {
  30800. __extends(StopAnimationAction, _super);
  30801. function StopAnimationAction(triggerOptions, target, condition) {
  30802. _super.call(this, triggerOptions, condition);
  30803. this._target = target;
  30804. }
  30805. StopAnimationAction.prototype._prepare = function () {
  30806. };
  30807. StopAnimationAction.prototype.execute = function () {
  30808. var scene = this._actionManager.getScene();
  30809. scene.stopAnimation(this._target);
  30810. };
  30811. return StopAnimationAction;
  30812. })(BABYLON.Action);
  30813. BABYLON.StopAnimationAction = StopAnimationAction;
  30814. var DoNothingAction = (function (_super) {
  30815. __extends(DoNothingAction, _super);
  30816. function DoNothingAction(triggerOptions, condition) {
  30817. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  30818. _super.call(this, triggerOptions, condition);
  30819. }
  30820. DoNothingAction.prototype.execute = function () {
  30821. };
  30822. return DoNothingAction;
  30823. })(BABYLON.Action);
  30824. BABYLON.DoNothingAction = DoNothingAction;
  30825. var CombineAction = (function (_super) {
  30826. __extends(CombineAction, _super);
  30827. function CombineAction(triggerOptions, children, condition) {
  30828. _super.call(this, triggerOptions, condition);
  30829. this.children = children;
  30830. }
  30831. CombineAction.prototype._prepare = function () {
  30832. for (var index = 0; index < this.children.length; index++) {
  30833. this.children[index]._actionManager = this._actionManager;
  30834. this.children[index]._prepare();
  30835. }
  30836. };
  30837. CombineAction.prototype.execute = function (evt) {
  30838. for (var index = 0; index < this.children.length; index++) {
  30839. this.children[index].execute(evt);
  30840. }
  30841. };
  30842. return CombineAction;
  30843. })(BABYLON.Action);
  30844. BABYLON.CombineAction = CombineAction;
  30845. var ExecuteCodeAction = (function (_super) {
  30846. __extends(ExecuteCodeAction, _super);
  30847. function ExecuteCodeAction(triggerOptions, func, condition) {
  30848. _super.call(this, triggerOptions, condition);
  30849. this.func = func;
  30850. }
  30851. ExecuteCodeAction.prototype.execute = function (evt) {
  30852. this.func(evt);
  30853. };
  30854. return ExecuteCodeAction;
  30855. })(BABYLON.Action);
  30856. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  30857. var SetParentAction = (function (_super) {
  30858. __extends(SetParentAction, _super);
  30859. function SetParentAction(triggerOptions, target, parent, condition) {
  30860. _super.call(this, triggerOptions, condition);
  30861. this._target = target;
  30862. this._parent = parent;
  30863. }
  30864. SetParentAction.prototype._prepare = function () {
  30865. };
  30866. SetParentAction.prototype.execute = function () {
  30867. if (this._target.parent === this._parent) {
  30868. return;
  30869. }
  30870. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  30871. invertParentWorldMatrix.invert();
  30872. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  30873. this._target.parent = this._parent;
  30874. };
  30875. return SetParentAction;
  30876. })(BABYLON.Action);
  30877. BABYLON.SetParentAction = SetParentAction;
  30878. var PlaySoundAction = (function (_super) {
  30879. __extends(PlaySoundAction, _super);
  30880. function PlaySoundAction(triggerOptions, sound, condition) {
  30881. _super.call(this, triggerOptions, condition);
  30882. this._sound = sound;
  30883. }
  30884. PlaySoundAction.prototype._prepare = function () {
  30885. };
  30886. PlaySoundAction.prototype.execute = function () {
  30887. if (this._sound !== undefined)
  30888. this._sound.play();
  30889. };
  30890. return PlaySoundAction;
  30891. })(BABYLON.Action);
  30892. BABYLON.PlaySoundAction = PlaySoundAction;
  30893. var StopSoundAction = (function (_super) {
  30894. __extends(StopSoundAction, _super);
  30895. function StopSoundAction(triggerOptions, sound, condition) {
  30896. _super.call(this, triggerOptions, condition);
  30897. this._sound = sound;
  30898. }
  30899. StopSoundAction.prototype._prepare = function () {
  30900. };
  30901. StopSoundAction.prototype.execute = function () {
  30902. if (this._sound !== undefined)
  30903. this._sound.stop();
  30904. };
  30905. return StopSoundAction;
  30906. })(BABYLON.Action);
  30907. BABYLON.StopSoundAction = StopSoundAction;
  30908. })(BABYLON || (BABYLON = {}));
  30909. var BABYLON;
  30910. (function (BABYLON) {
  30911. var Geometry = (function () {
  30912. function Geometry(id, scene, vertexData, updatable, mesh) {
  30913. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30914. this._totalVertices = 0;
  30915. this._isDisposed = false;
  30916. this.id = id;
  30917. this._engine = scene.getEngine();
  30918. this._meshes = [];
  30919. this._scene = scene;
  30920. //Init vertex buffer cache
  30921. this._vertexBuffers = {};
  30922. this._indices = [];
  30923. // vertexData
  30924. if (vertexData) {
  30925. this.setAllVerticesData(vertexData, updatable);
  30926. }
  30927. else {
  30928. this._totalVertices = 0;
  30929. this._indices = [];
  30930. }
  30931. // applyToMesh
  30932. if (mesh) {
  30933. if (mesh instanceof BABYLON.LinesMesh) {
  30934. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30935. this.updateExtend();
  30936. }
  30937. this.applyToMesh(mesh);
  30938. mesh.computeWorldMatrix(true);
  30939. }
  30940. }
  30941. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30942. /**
  30943. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  30944. * @returns The Bias Vector
  30945. */
  30946. get: function () {
  30947. return this._boundingBias;
  30948. },
  30949. set: function (value) {
  30950. if (this._boundingBias && this._boundingBias.equals(value)) {
  30951. return;
  30952. }
  30953. this._boundingBias = value.clone();
  30954. this.updateBoundingInfo(true, null);
  30955. },
  30956. enumerable: true,
  30957. configurable: true
  30958. });
  30959. Object.defineProperty(Geometry.prototype, "extend", {
  30960. get: function () {
  30961. return this._extend;
  30962. },
  30963. enumerable: true,
  30964. configurable: true
  30965. });
  30966. Geometry.prototype.getScene = function () {
  30967. return this._scene;
  30968. };
  30969. Geometry.prototype.getEngine = function () {
  30970. return this._engine;
  30971. };
  30972. Geometry.prototype.isReady = function () {
  30973. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30974. };
  30975. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30976. vertexData.applyToGeometry(this, updatable);
  30977. this.notifyUpdate();
  30978. };
  30979. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30980. if (this._vertexBuffers[kind]) {
  30981. this._vertexBuffers[kind].dispose();
  30982. }
  30983. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30984. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30985. stride = this._vertexBuffers[kind].getStrideSize();
  30986. this._totalVertices = data.length / stride;
  30987. this.updateExtend(data);
  30988. var meshes = this._meshes;
  30989. var numOfMeshes = meshes.length;
  30990. for (var index = 0; index < numOfMeshes; index++) {
  30991. var mesh = meshes[index];
  30992. mesh._resetPointsArrayCache();
  30993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30994. mesh._createGlobalSubMesh();
  30995. mesh.computeWorldMatrix(true);
  30996. }
  30997. }
  30998. this.notifyUpdate(kind);
  30999. };
  31000. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31001. var vertexBuffer = this.getVertexBuffer(kind);
  31002. if (!vertexBuffer) {
  31003. return;
  31004. }
  31005. vertexBuffer.updateDirectly(data, offset);
  31006. this.notifyUpdate(kind);
  31007. };
  31008. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31009. var vertexBuffer = this.getVertexBuffer(kind);
  31010. if (!vertexBuffer) {
  31011. return;
  31012. }
  31013. vertexBuffer.update(data);
  31014. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31015. var stride = vertexBuffer.getStrideSize();
  31016. this._totalVertices = data.length / stride;
  31017. this.updateBoundingInfo(updateExtends, data);
  31018. }
  31019. this.notifyUpdate(kind);
  31020. };
  31021. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31022. if (updateExtends) {
  31023. this.updateExtend(data);
  31024. }
  31025. var meshes = this._meshes;
  31026. var numOfMeshes = meshes.length;
  31027. for (var index = 0; index < numOfMeshes; index++) {
  31028. var mesh = meshes[index];
  31029. mesh._resetPointsArrayCache();
  31030. if (updateExtends) {
  31031. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31032. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31033. var subMesh = mesh.subMeshes[subIndex];
  31034. subMesh.refreshBoundingInfo();
  31035. }
  31036. }
  31037. }
  31038. };
  31039. Geometry.prototype.getTotalVertices = function () {
  31040. if (!this.isReady()) {
  31041. return 0;
  31042. }
  31043. return this._totalVertices;
  31044. };
  31045. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  31046. var vertexBuffer = this.getVertexBuffer(kind);
  31047. if (!vertexBuffer) {
  31048. return null;
  31049. }
  31050. var orig = vertexBuffer.getData();
  31051. if (!copyWhenShared || this._meshes.length === 1) {
  31052. return orig;
  31053. }
  31054. else {
  31055. var len = orig.length;
  31056. var copy = [];
  31057. for (var i = 0; i < len; i++) {
  31058. copy.push(orig[i]);
  31059. }
  31060. return copy;
  31061. }
  31062. };
  31063. Geometry.prototype.getVertexBuffer = function (kind) {
  31064. if (!this.isReady()) {
  31065. return null;
  31066. }
  31067. return this._vertexBuffers[kind];
  31068. };
  31069. Geometry.prototype.getVertexBuffers = function () {
  31070. if (!this.isReady()) {
  31071. return null;
  31072. }
  31073. return this._vertexBuffers;
  31074. };
  31075. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31076. if (!this._vertexBuffers) {
  31077. if (this._delayInfo) {
  31078. return this._delayInfo.indexOf(kind) !== -1;
  31079. }
  31080. return false;
  31081. }
  31082. return this._vertexBuffers[kind] !== undefined;
  31083. };
  31084. Geometry.prototype.getVerticesDataKinds = function () {
  31085. var result = [];
  31086. var kind;
  31087. if (!this._vertexBuffers && this._delayInfo) {
  31088. for (kind in this._delayInfo) {
  31089. result.push(kind);
  31090. }
  31091. }
  31092. else {
  31093. for (kind in this._vertexBuffers) {
  31094. result.push(kind);
  31095. }
  31096. }
  31097. return result;
  31098. };
  31099. Geometry.prototype.setIndices = function (indices, totalVertices) {
  31100. if (this._indexBuffer) {
  31101. this._engine._releaseBuffer(this._indexBuffer);
  31102. }
  31103. this._indices = indices;
  31104. if (this._meshes.length !== 0 && this._indices) {
  31105. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31106. }
  31107. if (totalVertices !== undefined) {
  31108. this._totalVertices = totalVertices;
  31109. }
  31110. var meshes = this._meshes;
  31111. var numOfMeshes = meshes.length;
  31112. for (var index = 0; index < numOfMeshes; index++) {
  31113. meshes[index]._createGlobalSubMesh();
  31114. }
  31115. this.notifyUpdate();
  31116. };
  31117. Geometry.prototype.getTotalIndices = function () {
  31118. if (!this.isReady()) {
  31119. return 0;
  31120. }
  31121. return this._indices.length;
  31122. };
  31123. Geometry.prototype.getIndices = function (copyWhenShared) {
  31124. if (!this.isReady()) {
  31125. return null;
  31126. }
  31127. var orig = this._indices;
  31128. if (!copyWhenShared || this._meshes.length === 1) {
  31129. return orig;
  31130. }
  31131. else {
  31132. var len = orig.length;
  31133. var copy = [];
  31134. for (var i = 0; i < len; i++) {
  31135. copy.push(orig[i]);
  31136. }
  31137. return copy;
  31138. }
  31139. };
  31140. Geometry.prototype.getIndexBuffer = function () {
  31141. if (!this.isReady()) {
  31142. return null;
  31143. }
  31144. return this._indexBuffer;
  31145. };
  31146. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31147. var meshes = this._meshes;
  31148. var index = meshes.indexOf(mesh);
  31149. if (index === -1) {
  31150. return;
  31151. }
  31152. for (var kind in this._vertexBuffers) {
  31153. this._vertexBuffers[kind].dispose();
  31154. }
  31155. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  31156. this._indexBuffer = null;
  31157. }
  31158. meshes.splice(index, 1);
  31159. mesh._geometry = null;
  31160. if (meshes.length === 0 && shouldDispose) {
  31161. this.dispose();
  31162. }
  31163. };
  31164. Geometry.prototype.applyToMesh = function (mesh) {
  31165. if (mesh._geometry === this) {
  31166. return;
  31167. }
  31168. var previousGeometry = mesh._geometry;
  31169. if (previousGeometry) {
  31170. previousGeometry.releaseForMesh(mesh);
  31171. }
  31172. var meshes = this._meshes;
  31173. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31174. mesh._geometry = this;
  31175. this._scene.pushGeometry(this);
  31176. meshes.push(mesh);
  31177. if (this.isReady()) {
  31178. this._applyToMesh(mesh);
  31179. }
  31180. else {
  31181. mesh._boundingInfo = this._boundingInfo;
  31182. }
  31183. };
  31184. Geometry.prototype.updateExtend = function (data) {
  31185. if (data === void 0) { data = null; }
  31186. if (!data) {
  31187. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31188. }
  31189. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  31190. };
  31191. Geometry.prototype._applyToMesh = function (mesh) {
  31192. var numOfMeshes = this._meshes.length;
  31193. // vertexBuffers
  31194. for (var kind in this._vertexBuffers) {
  31195. if (numOfMeshes === 1) {
  31196. this._vertexBuffers[kind].create();
  31197. }
  31198. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31199. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31200. mesh._resetPointsArrayCache();
  31201. if (!this._extend) {
  31202. this.updateExtend(this._vertexBuffers[kind].getData());
  31203. }
  31204. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31205. mesh._createGlobalSubMesh();
  31206. //bounding info was just created again, world matrix should be applied again.
  31207. mesh._updateBoundingInfo();
  31208. }
  31209. }
  31210. // indexBuffer
  31211. if (numOfMeshes === 1 && this._indices) {
  31212. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31213. }
  31214. if (this._indexBuffer) {
  31215. this._indexBuffer.references = numOfMeshes;
  31216. }
  31217. };
  31218. Geometry.prototype.notifyUpdate = function (kind) {
  31219. if (this.onGeometryUpdated) {
  31220. this.onGeometryUpdated(this, kind);
  31221. }
  31222. };
  31223. Geometry.prototype.load = function (scene, onLoaded) {
  31224. var _this = this;
  31225. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31226. return;
  31227. }
  31228. if (this.isReady()) {
  31229. if (onLoaded) {
  31230. onLoaded();
  31231. }
  31232. return;
  31233. }
  31234. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31235. scene._addPendingData(this);
  31236. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31237. _this._delayLoadingFunction(JSON.parse(data), _this);
  31238. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31239. _this._delayInfo = [];
  31240. scene._removePendingData(_this);
  31241. var meshes = _this._meshes;
  31242. var numOfMeshes = meshes.length;
  31243. for (var index = 0; index < numOfMeshes; index++) {
  31244. _this._applyToMesh(meshes[index]);
  31245. }
  31246. if (onLoaded) {
  31247. onLoaded();
  31248. }
  31249. }, function () { }, scene.database);
  31250. };
  31251. Geometry.prototype.isDisposed = function () {
  31252. return this._isDisposed;
  31253. };
  31254. Geometry.prototype.dispose = function () {
  31255. var meshes = this._meshes;
  31256. var numOfMeshes = meshes.length;
  31257. var index;
  31258. for (index = 0; index < numOfMeshes; index++) {
  31259. this.releaseForMesh(meshes[index]);
  31260. }
  31261. this._meshes = [];
  31262. for (var kind in this._vertexBuffers) {
  31263. this._vertexBuffers[kind].dispose();
  31264. }
  31265. this._vertexBuffers = [];
  31266. this._totalVertices = 0;
  31267. if (this._indexBuffer) {
  31268. this._engine._releaseBuffer(this._indexBuffer);
  31269. }
  31270. this._indexBuffer = null;
  31271. this._indices = [];
  31272. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31273. this.delayLoadingFile = null;
  31274. this._delayLoadingFunction = null;
  31275. this._delayInfo = [];
  31276. this._boundingInfo = null;
  31277. this._scene.removeGeometry(this);
  31278. this._isDisposed = true;
  31279. };
  31280. Geometry.prototype.copy = function (id) {
  31281. var vertexData = new BABYLON.VertexData();
  31282. vertexData.indices = [];
  31283. var indices = this.getIndices();
  31284. for (var index = 0; index < indices.length; index++) {
  31285. vertexData.indices.push(indices[index]);
  31286. }
  31287. var updatable = false;
  31288. var stopChecking = false;
  31289. var kind;
  31290. for (kind in this._vertexBuffers) {
  31291. // using slice() to make a copy of the array and not just reference it
  31292. var data = this.getVerticesData(kind);
  31293. if (data instanceof Float32Array) {
  31294. vertexData.set(new Float32Array(data), kind);
  31295. }
  31296. else {
  31297. vertexData.set(data.slice(0), kind);
  31298. }
  31299. if (!stopChecking) {
  31300. updatable = this.getVertexBuffer(kind).isUpdatable();
  31301. stopChecking = !updatable;
  31302. }
  31303. }
  31304. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31305. geometry.delayLoadState = this.delayLoadState;
  31306. geometry.delayLoadingFile = this.delayLoadingFile;
  31307. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31308. for (kind in this._delayInfo) {
  31309. geometry._delayInfo = geometry._delayInfo || [];
  31310. geometry._delayInfo.push(kind);
  31311. }
  31312. // Bounding info
  31313. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31314. return geometry;
  31315. };
  31316. Geometry.prototype.serialize = function () {
  31317. var serializationObject = {};
  31318. serializationObject.id = this.id;
  31319. if (BABYLON.Tags.HasTags(this)) {
  31320. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31321. }
  31322. return serializationObject;
  31323. };
  31324. Geometry.prototype.serializeVerticeData = function () {
  31325. var serializationObject = this.serialize();
  31326. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31327. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31328. }
  31329. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31330. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31331. }
  31332. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31333. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31334. }
  31335. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31336. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31337. }
  31338. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31339. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31340. }
  31341. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31342. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31343. }
  31344. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31345. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31346. }
  31347. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31348. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31349. }
  31350. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31351. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31352. }
  31353. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31354. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31355. serializationObject.matricesIndices._isExpanded = true;
  31356. }
  31357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31358. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31359. }
  31360. serializationObject.indices = this.getIndices();
  31361. return serializationObject;
  31362. };
  31363. // Statics
  31364. Geometry.ExtractFromMesh = function (mesh, id) {
  31365. var geometry = mesh._geometry;
  31366. if (!geometry) {
  31367. return null;
  31368. }
  31369. return geometry.copy(id);
  31370. };
  31371. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31372. // be aware Math.random() could cause collisions
  31373. Geometry.RandomId = function () {
  31374. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31375. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31376. return v.toString(16);
  31377. });
  31378. };
  31379. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31380. var scene = mesh.getScene();
  31381. // Geometry
  31382. var geometryId = parsedGeometry.geometryId;
  31383. if (geometryId) {
  31384. var geometry = scene.getGeometryByID(geometryId);
  31385. if (geometry) {
  31386. geometry.applyToMesh(mesh);
  31387. }
  31388. }
  31389. else if (parsedGeometry instanceof ArrayBuffer) {
  31390. var binaryInfo = mesh._binaryInfo;
  31391. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31392. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31393. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31394. }
  31395. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31396. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31397. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31398. }
  31399. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31400. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31401. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31402. }
  31403. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31404. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31405. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31406. }
  31407. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31408. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31409. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31410. }
  31411. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31412. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31413. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31414. }
  31415. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31416. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31417. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31418. }
  31419. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31420. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31421. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31422. }
  31423. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31424. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31425. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31426. }
  31427. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31428. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31429. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31430. }
  31431. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31432. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31433. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31434. }
  31435. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31436. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31437. mesh.setIndices(indicesData);
  31438. }
  31439. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31440. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31441. mesh.subMeshes = [];
  31442. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31443. var materialIndex = subMeshesData[(i * 5) + 0];
  31444. var verticesStart = subMeshesData[(i * 5) + 1];
  31445. var verticesCount = subMeshesData[(i * 5) + 2];
  31446. var indexStart = subMeshesData[(i * 5) + 3];
  31447. var indexCount = subMeshesData[(i * 5) + 4];
  31448. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31449. }
  31450. }
  31451. }
  31452. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31453. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31454. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31455. if (parsedGeometry.uvs) {
  31456. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31457. }
  31458. if (parsedGeometry.uvs2) {
  31459. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31460. }
  31461. if (parsedGeometry.uvs3) {
  31462. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31463. }
  31464. if (parsedGeometry.uvs4) {
  31465. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31466. }
  31467. if (parsedGeometry.uvs5) {
  31468. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31469. }
  31470. if (parsedGeometry.uvs6) {
  31471. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31472. }
  31473. if (parsedGeometry.colors) {
  31474. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31475. }
  31476. if (parsedGeometry.matricesIndices) {
  31477. if (!parsedGeometry.matricesIndices._isExpanded) {
  31478. var floatIndices = [];
  31479. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31480. var matricesIndex = parsedGeometry.matricesIndices[i];
  31481. floatIndices.push(matricesIndex & 0x000000FF);
  31482. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31483. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31484. floatIndices.push(matricesIndex >> 24);
  31485. }
  31486. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31487. }
  31488. else {
  31489. delete parsedGeometry.matricesIndices._isExpanded;
  31490. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31491. }
  31492. }
  31493. if (parsedGeometry.matricesIndicesExtra) {
  31494. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31495. var floatIndices = [];
  31496. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31497. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31498. floatIndices.push(matricesIndex & 0x000000FF);
  31499. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31500. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31501. floatIndices.push(matricesIndex >> 24);
  31502. }
  31503. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  31504. }
  31505. else {
  31506. delete parsedGeometry.matricesIndices._isExpanded;
  31507. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  31508. }
  31509. }
  31510. if (parsedGeometry.matricesWeights) {
  31511. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  31512. }
  31513. if (parsedGeometry.matricesWeightsExtra) {
  31514. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  31515. }
  31516. mesh.setIndices(parsedGeometry.indices);
  31517. }
  31518. // SubMeshes
  31519. if (parsedGeometry.subMeshes) {
  31520. mesh.subMeshes = [];
  31521. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31522. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31523. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31524. }
  31525. }
  31526. // Flat shading
  31527. if (mesh._shouldGenerateFlatShading) {
  31528. mesh.convertToFlatShadedMesh();
  31529. delete mesh._shouldGenerateFlatShading;
  31530. }
  31531. // Update
  31532. mesh.computeWorldMatrix(true);
  31533. // Octree
  31534. if (scene['_selectionOctree']) {
  31535. scene['_selectionOctree'].addMesh(mesh);
  31536. }
  31537. };
  31538. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31539. if (scene.getGeometryByID(parsedVertexData.id)) {
  31540. return null; // null since geometry could be something else than a box...
  31541. }
  31542. var geometry = new Geometry(parsedVertexData.id, scene);
  31543. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31544. if (parsedVertexData.delayLoadingFile) {
  31545. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31546. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31547. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31548. geometry._delayInfo = [];
  31549. if (parsedVertexData.hasUVs) {
  31550. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31551. }
  31552. if (parsedVertexData.hasUVs2) {
  31553. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31554. }
  31555. if (parsedVertexData.hasUVs3) {
  31556. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31557. }
  31558. if (parsedVertexData.hasUVs4) {
  31559. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31560. }
  31561. if (parsedVertexData.hasUVs5) {
  31562. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31563. }
  31564. if (parsedVertexData.hasUVs6) {
  31565. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31566. }
  31567. if (parsedVertexData.hasColors) {
  31568. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31569. }
  31570. if (parsedVertexData.hasMatricesIndices) {
  31571. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31572. }
  31573. if (parsedVertexData.hasMatricesWeights) {
  31574. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31575. }
  31576. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31577. }
  31578. else {
  31579. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31580. }
  31581. scene.pushGeometry(geometry, true);
  31582. return geometry;
  31583. };
  31584. return Geometry;
  31585. })();
  31586. BABYLON.Geometry = Geometry;
  31587. /////// Primitives //////////////////////////////////////////////
  31588. var Geometry;
  31589. (function (Geometry) {
  31590. var Primitives;
  31591. (function (Primitives) {
  31592. /// Abstract class
  31593. var _Primitive = (function (_super) {
  31594. __extends(_Primitive, _super);
  31595. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31596. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  31597. this._canBeRegenerated = _canBeRegenerated;
  31598. this._beingRegenerated = true;
  31599. this.regenerate();
  31600. this._beingRegenerated = false;
  31601. }
  31602. _Primitive.prototype.canBeRegenerated = function () {
  31603. return this._canBeRegenerated;
  31604. };
  31605. _Primitive.prototype.regenerate = function () {
  31606. if (!this._canBeRegenerated) {
  31607. return;
  31608. }
  31609. this._beingRegenerated = true;
  31610. this.setAllVerticesData(this._regenerateVertexData(), false);
  31611. this._beingRegenerated = false;
  31612. };
  31613. _Primitive.prototype.asNewGeometry = function (id) {
  31614. return _super.prototype.copy.call(this, id);
  31615. };
  31616. // overrides
  31617. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31618. if (!this._beingRegenerated) {
  31619. return;
  31620. }
  31621. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31622. };
  31623. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31624. if (!this._beingRegenerated) {
  31625. return;
  31626. }
  31627. _super.prototype.setVerticesData.call(this, kind, data, false);
  31628. };
  31629. // to override
  31630. // protected
  31631. _Primitive.prototype._regenerateVertexData = function () {
  31632. throw new Error("Abstract method");
  31633. };
  31634. _Primitive.prototype.copy = function (id) {
  31635. throw new Error("Must be overriden in sub-classes.");
  31636. };
  31637. _Primitive.prototype.serialize = function () {
  31638. var serializationObject = _super.prototype.serialize.call(this);
  31639. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31640. return serializationObject;
  31641. };
  31642. return _Primitive;
  31643. })(Geometry);
  31644. Primitives._Primitive = _Primitive;
  31645. var Ribbon = (function (_super) {
  31646. __extends(Ribbon, _super);
  31647. // Members
  31648. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31649. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31650. _super.call(this, id, scene, canBeRegenerated, mesh);
  31651. this.pathArray = pathArray;
  31652. this.closeArray = closeArray;
  31653. this.closePath = closePath;
  31654. this.offset = offset;
  31655. this.side = side;
  31656. }
  31657. Ribbon.prototype._regenerateVertexData = function () {
  31658. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31659. };
  31660. Ribbon.prototype.copy = function (id) {
  31661. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  31662. };
  31663. return Ribbon;
  31664. })(_Primitive);
  31665. Primitives.Ribbon = Ribbon;
  31666. var Box = (function (_super) {
  31667. __extends(Box, _super);
  31668. // Members
  31669. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31671. _super.call(this, id, scene, canBeRegenerated, mesh);
  31672. this.size = size;
  31673. this.side = side;
  31674. }
  31675. Box.prototype._regenerateVertexData = function () {
  31676. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31677. };
  31678. Box.prototype.copy = function (id) {
  31679. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31680. };
  31681. Box.prototype.serialize = function () {
  31682. var serializationObject = _super.prototype.serialize.call(this);
  31683. serializationObject.size = this.size;
  31684. return serializationObject;
  31685. };
  31686. Box.Parse = function (parsedBox, scene) {
  31687. if (scene.getGeometryByID(parsedBox.id)) {
  31688. return null; // null since geometry could be something else than a box...
  31689. }
  31690. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31691. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31692. scene.pushGeometry(box, true);
  31693. return box;
  31694. };
  31695. return Box;
  31696. })(_Primitive);
  31697. Primitives.Box = Box;
  31698. var Sphere = (function (_super) {
  31699. __extends(Sphere, _super);
  31700. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31701. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31702. _super.call(this, id, scene, canBeRegenerated, mesh);
  31703. this.segments = segments;
  31704. this.diameter = diameter;
  31705. this.side = side;
  31706. }
  31707. Sphere.prototype._regenerateVertexData = function () {
  31708. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31709. };
  31710. Sphere.prototype.copy = function (id) {
  31711. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31712. };
  31713. Sphere.prototype.serialize = function () {
  31714. var serializationObject = _super.prototype.serialize.call(this);
  31715. serializationObject.segments = this.segments;
  31716. serializationObject.diameter = this.diameter;
  31717. return serializationObject;
  31718. };
  31719. Sphere.Parse = function (parsedSphere, scene) {
  31720. if (scene.getGeometryByID(parsedSphere.id)) {
  31721. return null; // null since geometry could be something else than a sphere...
  31722. }
  31723. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31724. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31725. scene.pushGeometry(sphere, true);
  31726. return sphere;
  31727. };
  31728. return Sphere;
  31729. })(_Primitive);
  31730. Primitives.Sphere = Sphere;
  31731. var Disc = (function (_super) {
  31732. __extends(Disc, _super);
  31733. // Members
  31734. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31735. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31736. _super.call(this, id, scene, canBeRegenerated, mesh);
  31737. this.radius = radius;
  31738. this.tessellation = tessellation;
  31739. this.side = side;
  31740. }
  31741. Disc.prototype._regenerateVertexData = function () {
  31742. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31743. };
  31744. Disc.prototype.copy = function (id) {
  31745. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31746. };
  31747. return Disc;
  31748. })(_Primitive);
  31749. Primitives.Disc = Disc;
  31750. var Cylinder = (function (_super) {
  31751. __extends(Cylinder, _super);
  31752. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31753. if (subdivisions === void 0) { subdivisions = 1; }
  31754. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31755. _super.call(this, id, scene, canBeRegenerated, mesh);
  31756. this.height = height;
  31757. this.diameterTop = diameterTop;
  31758. this.diameterBottom = diameterBottom;
  31759. this.tessellation = tessellation;
  31760. this.subdivisions = subdivisions;
  31761. this.side = side;
  31762. }
  31763. Cylinder.prototype._regenerateVertexData = function () {
  31764. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31765. };
  31766. Cylinder.prototype.copy = function (id) {
  31767. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31768. };
  31769. Cylinder.prototype.serialize = function () {
  31770. var serializationObject = _super.prototype.serialize.call(this);
  31771. serializationObject.height = this.height;
  31772. serializationObject.diameterTop = this.diameterTop;
  31773. serializationObject.diameterBottom = this.diameterBottom;
  31774. serializationObject.tessellation = this.tessellation;
  31775. return serializationObject;
  31776. };
  31777. Cylinder.Parse = function (parsedCylinder, scene) {
  31778. if (scene.getGeometryByID(parsedCylinder.id)) {
  31779. return null; // null since geometry could be something else than a cylinder...
  31780. }
  31781. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31782. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31783. scene.pushGeometry(cylinder, true);
  31784. return cylinder;
  31785. };
  31786. return Cylinder;
  31787. })(_Primitive);
  31788. Primitives.Cylinder = Cylinder;
  31789. var Torus = (function (_super) {
  31790. __extends(Torus, _super);
  31791. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31792. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31793. _super.call(this, id, scene, canBeRegenerated, mesh);
  31794. this.diameter = diameter;
  31795. this.thickness = thickness;
  31796. this.tessellation = tessellation;
  31797. this.side = side;
  31798. }
  31799. Torus.prototype._regenerateVertexData = function () {
  31800. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31801. };
  31802. Torus.prototype.copy = function (id) {
  31803. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31804. };
  31805. Torus.prototype.serialize = function () {
  31806. var serializationObject = _super.prototype.serialize.call(this);
  31807. serializationObject.diameter = this.diameter;
  31808. serializationObject.thickness = this.thickness;
  31809. serializationObject.tessellation = this.tessellation;
  31810. return serializationObject;
  31811. };
  31812. Torus.Parse = function (parsedTorus, scene) {
  31813. if (scene.getGeometryByID(parsedTorus.id)) {
  31814. return null; // null since geometry could be something else than a torus...
  31815. }
  31816. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31817. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31818. scene.pushGeometry(torus, true);
  31819. return torus;
  31820. };
  31821. return Torus;
  31822. })(_Primitive);
  31823. Primitives.Torus = Torus;
  31824. var Ground = (function (_super) {
  31825. __extends(Ground, _super);
  31826. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31827. _super.call(this, id, scene, canBeRegenerated, mesh);
  31828. this.width = width;
  31829. this.height = height;
  31830. this.subdivisions = subdivisions;
  31831. }
  31832. Ground.prototype._regenerateVertexData = function () {
  31833. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31834. };
  31835. Ground.prototype.copy = function (id) {
  31836. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31837. };
  31838. Ground.prototype.serialize = function () {
  31839. var serializationObject = _super.prototype.serialize.call(this);
  31840. serializationObject.width = this.width;
  31841. serializationObject.height = this.height;
  31842. serializationObject.subdivisions = this.subdivisions;
  31843. return serializationObject;
  31844. };
  31845. Ground.Parse = function (parsedGround, scene) {
  31846. if (scene.getGeometryByID(parsedGround.id)) {
  31847. return null; // null since geometry could be something else than a ground...
  31848. }
  31849. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31850. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31851. scene.pushGeometry(ground, true);
  31852. return ground;
  31853. };
  31854. return Ground;
  31855. })(_Primitive);
  31856. Primitives.Ground = Ground;
  31857. var TiledGround = (function (_super) {
  31858. __extends(TiledGround, _super);
  31859. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31860. _super.call(this, id, scene, canBeRegenerated, mesh);
  31861. this.xmin = xmin;
  31862. this.zmin = zmin;
  31863. this.xmax = xmax;
  31864. this.zmax = zmax;
  31865. this.subdivisions = subdivisions;
  31866. this.precision = precision;
  31867. }
  31868. TiledGround.prototype._regenerateVertexData = function () {
  31869. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31870. };
  31871. TiledGround.prototype.copy = function (id) {
  31872. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31873. };
  31874. return TiledGround;
  31875. })(_Primitive);
  31876. Primitives.TiledGround = TiledGround;
  31877. var Plane = (function (_super) {
  31878. __extends(Plane, _super);
  31879. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31880. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31881. _super.call(this, id, scene, canBeRegenerated, mesh);
  31882. this.size = size;
  31883. this.side = side;
  31884. }
  31885. Plane.prototype._regenerateVertexData = function () {
  31886. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31887. };
  31888. Plane.prototype.copy = function (id) {
  31889. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31890. };
  31891. Plane.prototype.serialize = function () {
  31892. var serializationObject = _super.prototype.serialize.call(this);
  31893. serializationObject.size = this.size;
  31894. return serializationObject;
  31895. };
  31896. Plane.Parse = function (parsedPlane, scene) {
  31897. if (scene.getGeometryByID(parsedPlane.id)) {
  31898. return null; // null since geometry could be something else than a ground...
  31899. }
  31900. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31901. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31902. scene.pushGeometry(plane, true);
  31903. return plane;
  31904. };
  31905. return Plane;
  31906. })(_Primitive);
  31907. Primitives.Plane = Plane;
  31908. var TorusKnot = (function (_super) {
  31909. __extends(TorusKnot, _super);
  31910. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31911. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31912. _super.call(this, id, scene, canBeRegenerated, mesh);
  31913. this.radius = radius;
  31914. this.tube = tube;
  31915. this.radialSegments = radialSegments;
  31916. this.tubularSegments = tubularSegments;
  31917. this.p = p;
  31918. this.q = q;
  31919. this.side = side;
  31920. }
  31921. TorusKnot.prototype._regenerateVertexData = function () {
  31922. 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 });
  31923. };
  31924. TorusKnot.prototype.copy = function (id) {
  31925. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31926. };
  31927. TorusKnot.prototype.serialize = function () {
  31928. var serializationObject = _super.prototype.serialize.call(this);
  31929. serializationObject.radius = this.radius;
  31930. serializationObject.tube = this.tube;
  31931. serializationObject.radialSegments = this.radialSegments;
  31932. serializationObject.tubularSegments = this.tubularSegments;
  31933. serializationObject.p = this.p;
  31934. serializationObject.q = this.q;
  31935. return serializationObject;
  31936. };
  31937. ;
  31938. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31939. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31940. return null; // null since geometry could be something else than a ground...
  31941. }
  31942. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31943. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31944. scene.pushGeometry(torusKnot, true);
  31945. return torusKnot;
  31946. };
  31947. return TorusKnot;
  31948. })(_Primitive);
  31949. Primitives.TorusKnot = TorusKnot;
  31950. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31951. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31952. })(BABYLON || (BABYLON = {}));
  31953. var BABYLON;
  31954. (function (BABYLON) {
  31955. var GroundMesh = (function (_super) {
  31956. __extends(GroundMesh, _super);
  31957. function GroundMesh(name, scene) {
  31958. _super.call(this, name, scene);
  31959. this.generateOctree = false;
  31960. this._worldInverse = new BABYLON.Matrix();
  31961. }
  31962. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  31963. get: function () {
  31964. return this._subdivisions;
  31965. },
  31966. enumerable: true,
  31967. configurable: true
  31968. });
  31969. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  31970. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  31971. this._subdivisions = chunksCount;
  31972. this.subdivide(this._subdivisions);
  31973. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  31974. };
  31975. /**
  31976. * Returns a height (y) value in the Worl system :
  31977. * the ground altitude at the coordinates (x, z) expressed in the World system.
  31978. * Returns the ground y position if (x, z) are outside the ground surface.
  31979. * Not pertinent if the ground is rotated.
  31980. */
  31981. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  31982. // express x and y in the ground local system
  31983. x -= this.position.x;
  31984. z -= this.position.z;
  31985. x /= this.scaling.x;
  31986. z /= this.scaling.z;
  31987. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31988. return this.position.y;
  31989. }
  31990. if (!this._heightQuads || this._heightQuads.length == 0) {
  31991. this._initHeightQuads();
  31992. this._computeHeightQuads();
  31993. }
  31994. var facet = this._getFacetAt(x, z);
  31995. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  31996. // return y in the World system
  31997. return y * this.scaling.y + this.position.y;
  31998. };
  31999. /**
  32000. * Returns a normalized vector (Vector3) orthogonal to the ground
  32001. * at the ground coordinates (x, z) expressed in the World system.
  32002. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  32003. * Not pertinent if the ground is rotated.
  32004. */
  32005. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  32006. var normal = new BABYLON.Vector3(0, 1, 0);
  32007. this.getNormalAtCoordinatesToRef(x, z, normal);
  32008. return normal;
  32009. };
  32010. /**
  32011. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  32012. * at the ground coordinates (x, z) expressed in the World system.
  32013. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  32014. * Not pertinent if the ground is rotated.
  32015. */
  32016. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  32017. // express x and y in the ground local system
  32018. x -= this.position.x;
  32019. z -= this.position.z;
  32020. x /= this.scaling.x;
  32021. z /= this.scaling.z;
  32022. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32023. return;
  32024. }
  32025. if (!this._heightQuads || this._heightQuads.length == 0) {
  32026. this._initHeightQuads();
  32027. this._computeHeightQuads();
  32028. }
  32029. var facet = this._getFacetAt(x, z);
  32030. ref.x = facet.x;
  32031. ref.y = facet.y;
  32032. ref.z = facet.z;
  32033. };
  32034. /**
  32035. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  32036. * if the ground has been updated.
  32037. * This can be used in the render loop
  32038. */
  32039. GroundMesh.prototype.updateCoordinateHeights = function () {
  32040. if (!this._heightQuads || this._heightQuads.length == 0) {
  32041. this._initHeightQuads();
  32042. }
  32043. this._computeHeightQuads();
  32044. };
  32045. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  32046. GroundMesh.prototype._getFacetAt = function (x, z) {
  32047. // retrieve col and row from x, z coordinates in the ground local system
  32048. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  32049. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  32050. var quad = this._heightQuads[row * this._subdivisions + col];
  32051. var facet;
  32052. if (z < quad.slope.x * x + quad.slope.y) {
  32053. facet = quad.facet1;
  32054. }
  32055. else {
  32056. facet = quad.facet2;
  32057. }
  32058. return facet;
  32059. };
  32060. // Creates and populates the heightMap array with "facet" elements :
  32061. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  32062. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32063. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32064. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32065. GroundMesh.prototype._initHeightQuads = function () {
  32066. this._heightQuads = new Array();
  32067. for (var row = 0; row < this._subdivisions; row++) {
  32068. for (var col = 0; col < this._subdivisions; col++) {
  32069. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  32070. this._heightQuads[row * this._subdivisions + col] = quad;
  32071. }
  32072. }
  32073. };
  32074. // Compute each quad element values and update the the heightMap array :
  32075. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32076. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32077. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32078. GroundMesh.prototype._computeHeightQuads = function () {
  32079. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32080. var v1 = BABYLON.Tmp.Vector3[0];
  32081. var v2 = BABYLON.Tmp.Vector3[1];
  32082. var v3 = BABYLON.Tmp.Vector3[2];
  32083. var v4 = BABYLON.Tmp.Vector3[3];
  32084. var v1v2 = BABYLON.Tmp.Vector3[4];
  32085. var v1v3 = BABYLON.Tmp.Vector3[5];
  32086. var v1v4 = BABYLON.Tmp.Vector3[6];
  32087. var norm1 = BABYLON.Tmp.Vector3[7];
  32088. var norm2 = BABYLON.Tmp.Vector3[8];
  32089. var i = 0;
  32090. var j = 0;
  32091. var k = 0;
  32092. var cd = 0; // 2D slope coefficient : z = cd * x + h
  32093. var h = 0;
  32094. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  32095. var d2 = 0;
  32096. for (var row = 0; row < this._subdivisions; row++) {
  32097. for (var col = 0; col < this._subdivisions; col++) {
  32098. i = col * 3;
  32099. j = row * (this._subdivisions + 1) * 3;
  32100. k = (row + 1) * (this._subdivisions + 1) * 3;
  32101. v1.x = positions[j + i];
  32102. v1.y = positions[j + i + 1];
  32103. v1.z = positions[j + i + 2];
  32104. v2.x = positions[j + i + 3];
  32105. v2.y = positions[j + i + 4];
  32106. v2.z = positions[j + i + 5];
  32107. v3.x = positions[k + i];
  32108. v3.y = positions[k + i + 1];
  32109. v3.z = positions[k + i + 2];
  32110. v4.x = positions[k + i + 3];
  32111. v4.y = positions[k + i + 4];
  32112. v4.z = positions[k + i + 5];
  32113. // 2D slope V1V4
  32114. cd = (v4.z - v1.z) / (v4.x - v1.x);
  32115. h = v1.z - cd * v1.x; // v1 belongs to the slope
  32116. // facet equations :
  32117. // we compute each facet normal vector
  32118. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  32119. // we compute the value d by applying the equation to v1 which belongs to the plane
  32120. // then we store the facet equation in a Vector4
  32121. v2.subtractToRef(v1, v1v2);
  32122. v3.subtractToRef(v1, v1v3);
  32123. v4.subtractToRef(v1, v1v4);
  32124. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  32125. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  32126. norm1.normalize();
  32127. norm2.normalize();
  32128. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  32129. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  32130. var quad = this._heightQuads[row * this._subdivisions + col];
  32131. quad.slope.copyFromFloats(cd, h);
  32132. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  32133. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  32134. }
  32135. }
  32136. };
  32137. return GroundMesh;
  32138. })(BABYLON.Mesh);
  32139. BABYLON.GroundMesh = GroundMesh;
  32140. })(BABYLON || (BABYLON = {}));
  32141. var BABYLON;
  32142. (function (BABYLON) {
  32143. var LinesMesh = (function (_super) {
  32144. __extends(LinesMesh, _super);
  32145. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  32146. if (parent === void 0) { parent = null; }
  32147. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  32148. this.color = new BABYLON.Color3(1, 1, 1);
  32149. this.alpha = 1;
  32150. this._intersectionThreshold = 0.1;
  32151. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  32152. attributes: ["position"],
  32153. uniforms: ["worldViewProjection", "color"],
  32154. needAlphaBlending: true
  32155. });
  32156. }
  32157. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  32158. /**
  32159. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32160. * This margin is expressed in world space coordinates, so its value may vary.
  32161. * Default value is 0.1
  32162. * @returns the intersection Threshold value.
  32163. */
  32164. get: function () {
  32165. return this._intersectionThreshold;
  32166. },
  32167. /**
  32168. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32169. * This margin is expressed in world space coordinates, so its value may vary.
  32170. * @param value the new threshold to apply
  32171. */
  32172. set: function (value) {
  32173. if (this._intersectionThreshold === value) {
  32174. return;
  32175. }
  32176. this._intersectionThreshold = value;
  32177. if (this.geometry) {
  32178. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  32179. }
  32180. },
  32181. enumerable: true,
  32182. configurable: true
  32183. });
  32184. Object.defineProperty(LinesMesh.prototype, "material", {
  32185. get: function () {
  32186. return this._colorShader;
  32187. },
  32188. enumerable: true,
  32189. configurable: true
  32190. });
  32191. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  32192. get: function () {
  32193. return true;
  32194. },
  32195. enumerable: true,
  32196. configurable: true
  32197. });
  32198. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32199. get: function () {
  32200. return false;
  32201. },
  32202. enumerable: true,
  32203. configurable: true
  32204. });
  32205. LinesMesh.prototype.createInstance = function (name) {
  32206. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  32207. return null;
  32208. };
  32209. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32210. var engine = this.getScene().getEngine();
  32211. var indexToBind = this._geometry.getIndexBuffer();
  32212. // VBOs
  32213. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32214. // Color
  32215. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32216. };
  32217. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32218. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32219. return;
  32220. }
  32221. var engine = this.getScene().getEngine();
  32222. // Draw order
  32223. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32224. };
  32225. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32226. this._colorShader.dispose();
  32227. _super.prototype.dispose.call(this, doNotRecurse);
  32228. };
  32229. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32230. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32231. };
  32232. return LinesMesh;
  32233. })(BABYLON.Mesh);
  32234. BABYLON.LinesMesh = LinesMesh;
  32235. })(BABYLON || (BABYLON = {}));
  32236. var BABYLON;
  32237. (function (BABYLON) {
  32238. var DebugLayer = (function () {
  32239. function DebugLayer(scene) {
  32240. var _this = this;
  32241. this._transformationMatrix = BABYLON.Matrix.Identity();
  32242. this._enabled = false;
  32243. this._labelsEnabled = false;
  32244. this._displayStatistics = true;
  32245. this._displayTree = false;
  32246. this._displayLogs = false;
  32247. this._skeletonViewers = new Array();
  32248. this._identityMatrix = BABYLON.Matrix.Identity();
  32249. this.axisRatio = 0.02;
  32250. this.accentColor = "orange";
  32251. this._scene = scene;
  32252. this._syncPositions = function () {
  32253. var engine = _this._scene.getEngine();
  32254. var canvasRect = engine.getRenderingCanvasClientRect();
  32255. if (_this._showUI) {
  32256. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32257. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32258. _this._statsDiv.style.width = "400px";
  32259. _this._statsDiv.style.height = "auto";
  32260. _this._statsSubsetDiv.style.maxHeight = "240px";
  32261. _this._optionsDiv.style.left = "0px";
  32262. _this._optionsDiv.style.top = "10px";
  32263. _this._optionsDiv.style.width = "200px";
  32264. _this._optionsDiv.style.height = "auto";
  32265. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32266. _this._logDiv.style.left = "0px";
  32267. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32268. _this._logDiv.style.width = "600px";
  32269. _this._logDiv.style.height = "160px";
  32270. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32271. _this._treeDiv.style.top = "10px";
  32272. _this._treeDiv.style.width = "300px";
  32273. _this._treeDiv.style.height = "auto";
  32274. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32275. }
  32276. _this._globalDiv.style.left = canvasRect.left + "px";
  32277. _this._globalDiv.style.top = canvasRect.top + "px";
  32278. _this._drawingCanvas.style.left = "0px";
  32279. _this._drawingCanvas.style.top = "0px";
  32280. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32281. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32282. var devicePixelRatio = window.devicePixelRatio || 1;
  32283. var context = _this._drawingContext;
  32284. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32285. context.mozBackingStorePixelRatio ||
  32286. context.msBackingStorePixelRatio ||
  32287. context.oBackingStorePixelRatio ||
  32288. context.backingStorePixelRatio || 1;
  32289. _this._ratio = devicePixelRatio / backingStoreRatio;
  32290. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32291. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32292. };
  32293. this._onCanvasClick = function (evt) {
  32294. _this._clickPosition = {
  32295. x: evt.clientX * _this._ratio,
  32296. y: evt.clientY * _this._ratio
  32297. };
  32298. };
  32299. this._syncUI = function () {
  32300. if (_this._showUI) {
  32301. if (_this._displayStatistics) {
  32302. _this._displayStats();
  32303. _this._statsDiv.style.display = "";
  32304. }
  32305. else {
  32306. _this._statsDiv.style.display = "none";
  32307. }
  32308. if (_this._displayLogs) {
  32309. _this._logDiv.style.display = "";
  32310. }
  32311. else {
  32312. _this._logDiv.style.display = "none";
  32313. }
  32314. if (_this._displayTree) {
  32315. _this._treeDiv.style.display = "";
  32316. if (_this._needToRefreshMeshesTree) {
  32317. _this._needToRefreshMeshesTree = false;
  32318. _this._refreshMeshesTreeContent();
  32319. }
  32320. }
  32321. else {
  32322. _this._treeDiv.style.display = "none";
  32323. }
  32324. }
  32325. };
  32326. this._syncData = function () {
  32327. if (_this._labelsEnabled || !_this._showUI) {
  32328. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32329. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32330. var engine = _this._scene.getEngine();
  32331. var viewport = _this._camera.viewport;
  32332. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32333. // Meshes
  32334. var meshes = _this._camera.getActiveMeshes();
  32335. var index;
  32336. var projectedPosition;
  32337. for (index = 0; index < meshes.length; index++) {
  32338. var mesh = meshes.data[index];
  32339. var position = mesh.getBoundingInfo().boundingSphere.center;
  32340. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32341. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32342. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32343. }
  32344. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32345. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32346. }
  32347. }
  32348. // Cameras
  32349. var cameras = _this._scene.cameras;
  32350. for (index = 0; index < cameras.length; index++) {
  32351. var camera = cameras[index];
  32352. if (camera === _this._camera) {
  32353. continue;
  32354. }
  32355. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32356. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32357. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32358. _this._camera.detachControl(engine.getRenderingCanvas());
  32359. _this._camera = camera;
  32360. _this._camera.attachControl(engine.getRenderingCanvas());
  32361. }, function () { return "purple"; });
  32362. }
  32363. }
  32364. // Lights
  32365. var lights = _this._scene.lights;
  32366. for (index = 0; index < lights.length; index++) {
  32367. var light = lights[index];
  32368. if (light.position) {
  32369. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32370. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32371. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32372. light.setEnabled(!light.isEnabled());
  32373. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32374. }
  32375. }
  32376. }
  32377. }
  32378. _this._clickPosition = undefined;
  32379. };
  32380. }
  32381. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32382. while (this._treeSubsetDiv.hasChildNodes()) {
  32383. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32384. }
  32385. // Add meshes
  32386. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32387. sortedArray.sort(function (a, b) {
  32388. if (a.name === b.name) {
  32389. return 0;
  32390. }
  32391. return (a.name > b.name) ? 1 : -1;
  32392. });
  32393. for (var index = 0; index < sortedArray.length; index++) {
  32394. var mesh = sortedArray[index];
  32395. if (!mesh.isEnabled()) {
  32396. continue;
  32397. }
  32398. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32399. m.isVisible = element.checked;
  32400. }, mesh);
  32401. }
  32402. };
  32403. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32404. this._drawingContext.beginPath();
  32405. this._drawingContext.moveTo(zero.x, zero.y);
  32406. this._drawingContext.lineTo(unit.x, unit.y);
  32407. this._drawingContext.strokeStyle = color;
  32408. this._drawingContext.lineWidth = 4;
  32409. this._drawingContext.stroke();
  32410. this._drawingContext.font = "normal 14px Segoe UI";
  32411. this._drawingContext.fillStyle = color;
  32412. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32413. };
  32414. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32415. var position = mesh.getBoundingInfo().boundingSphere.center;
  32416. var worldMatrix = mesh.getWorldMatrix();
  32417. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32418. var unit = (unprojectedVector.subtract(position)).length();
  32419. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32420. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32421. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32422. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32423. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32424. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32425. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32426. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32427. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32428. };
  32429. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32430. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32431. this._drawingContext.font = "normal 12px Segoe UI";
  32432. var textMetrics = this._drawingContext.measureText(text);
  32433. var centerX = projectedPosition.x - textMetrics.width / 2;
  32434. var centerY = projectedPosition.y;
  32435. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32436. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32437. onClick();
  32438. }
  32439. this._drawingContext.beginPath();
  32440. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32441. this._drawingContext.fillStyle = getFillStyle();
  32442. this._drawingContext.globalAlpha = 0.5;
  32443. this._drawingContext.fill();
  32444. this._drawingContext.globalAlpha = 1.0;
  32445. this._drawingContext.strokeStyle = '#FFFFFF';
  32446. this._drawingContext.lineWidth = 1;
  32447. this._drawingContext.stroke();
  32448. this._drawingContext.fillStyle = "#FFFFFF";
  32449. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32450. this._drawingContext.beginPath();
  32451. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32452. this._drawingContext.fill();
  32453. }
  32454. };
  32455. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32456. if (!this._clickPosition) {
  32457. return false;
  32458. }
  32459. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32460. return false;
  32461. }
  32462. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32463. return false;
  32464. }
  32465. return true;
  32466. };
  32467. DebugLayer.prototype.isVisible = function () {
  32468. return this._enabled;
  32469. };
  32470. DebugLayer.prototype.hide = function () {
  32471. if (!this._enabled) {
  32472. return;
  32473. }
  32474. this._enabled = false;
  32475. var engine = this._scene.getEngine();
  32476. this._scene.unregisterBeforeRender(this._syncData);
  32477. this._scene.unregisterAfterRender(this._syncUI);
  32478. this._rootElement.removeChild(this._globalDiv);
  32479. this._scene.forceShowBoundingBoxes = false;
  32480. this._scene.forceWireframe = false;
  32481. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32482. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32483. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32484. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32485. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32486. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32487. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32488. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32489. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32490. this._scene.shadowsEnabled = true;
  32491. this._scene.particlesEnabled = true;
  32492. this._scene.postProcessesEnabled = true;
  32493. this._scene.collisionsEnabled = true;
  32494. this._scene.lightsEnabled = true;
  32495. this._scene.texturesEnabled = true;
  32496. this._scene.lensFlaresEnabled = true;
  32497. this._scene.proceduralTexturesEnabled = true;
  32498. this._scene.renderTargetsEnabled = true;
  32499. this._scene.probesEnabled = true;
  32500. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  32501. this._clearSkeletonViewers();
  32502. };
  32503. DebugLayer.prototype._clearSkeletonViewers = function () {
  32504. for (var index = 0; index < this._skeletonViewers.length; index++) {
  32505. this._skeletonViewers[index].dispose();
  32506. }
  32507. this._skeletonViewers = [];
  32508. };
  32509. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  32510. if (showUI === void 0) { showUI = true; }
  32511. if (camera === void 0) { camera = null; }
  32512. if (rootElement === void 0) { rootElement = null; }
  32513. if (this._enabled) {
  32514. return;
  32515. }
  32516. this._enabled = true;
  32517. if (camera) {
  32518. this._camera = camera;
  32519. }
  32520. else {
  32521. this._camera = this._scene.activeCamera;
  32522. }
  32523. this._showUI = showUI;
  32524. var engine = this._scene.getEngine();
  32525. this._globalDiv = document.createElement("div");
  32526. this._rootElement = rootElement || document.body;
  32527. this._rootElement.appendChild(this._globalDiv);
  32528. this._generateDOMelements();
  32529. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  32530. this._syncPositions();
  32531. this._scene.registerBeforeRender(this._syncData);
  32532. this._scene.registerAfterRender(this._syncUI);
  32533. };
  32534. DebugLayer.prototype._clearLabels = function () {
  32535. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  32536. for (var index = 0; index < this._scene.meshes.length; index++) {
  32537. var mesh = this._scene.meshes[index];
  32538. mesh.renderOverlay = false;
  32539. }
  32540. };
  32541. DebugLayer.prototype._generateheader = function (root, text) {
  32542. var header = document.createElement("div");
  32543. header.innerHTML = text + "&nbsp;";
  32544. header.style.textAlign = "right";
  32545. header.style.width = "100%";
  32546. header.style.color = "white";
  32547. header.style.backgroundColor = "Black";
  32548. header.style.padding = "5px 5px 4px 0px";
  32549. header.style.marginLeft = "-5px";
  32550. header.style.fontWeight = "bold";
  32551. root.appendChild(header);
  32552. };
  32553. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  32554. var label = document.createElement("label");
  32555. label.style.display = "inline";
  32556. label.innerHTML = title;
  32557. label.style.color = color;
  32558. root.appendChild(label);
  32559. root.appendChild(document.createElement("br"));
  32560. };
  32561. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  32562. if (tag === void 0) { tag = null; }
  32563. var label = document.createElement("label");
  32564. label.style.display = "inline";
  32565. var boundingBoxesCheckbox = document.createElement("input");
  32566. boundingBoxesCheckbox.type = "checkbox";
  32567. boundingBoxesCheckbox.checked = initialState;
  32568. boundingBoxesCheckbox.style.display = "inline";
  32569. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  32570. boundingBoxesCheckbox.style.verticalAlign = "sub";
  32571. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  32572. task(evt.target, tag);
  32573. });
  32574. label.appendChild(boundingBoxesCheckbox);
  32575. var container = document.createElement("span");
  32576. var leftPart = document.createElement("span");
  32577. var rightPart = document.createElement("span");
  32578. rightPart.style.cssFloat = "right";
  32579. leftPart.innerHTML = leftTitle;
  32580. rightPart.innerHTML = rightTitle;
  32581. rightPart.style.fontSize = "12px";
  32582. rightPart.style.maxWidth = "200px";
  32583. container.appendChild(leftPart);
  32584. container.appendChild(rightPart);
  32585. label.appendChild(container);
  32586. root.appendChild(label);
  32587. root.appendChild(document.createElement("br"));
  32588. };
  32589. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  32590. if (tag === void 0) { tag = null; }
  32591. var label = document.createElement("label");
  32592. label.style.display = "inline";
  32593. var checkBox = document.createElement("input");
  32594. checkBox.type = "checkbox";
  32595. checkBox.checked = initialState;
  32596. checkBox.style.display = "inline";
  32597. checkBox.style.margin = "0px 5px 0px 0px";
  32598. checkBox.style.verticalAlign = "sub";
  32599. checkBox.addEventListener("change", function (evt) {
  32600. task(evt.target, tag);
  32601. });
  32602. label.appendChild(checkBox);
  32603. label.appendChild(document.createTextNode(title));
  32604. root.appendChild(label);
  32605. root.appendChild(document.createElement("br"));
  32606. };
  32607. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  32608. if (tag === void 0) { tag = null; }
  32609. var button = document.createElement("button");
  32610. button.innerHTML = title;
  32611. button.style.height = "24px";
  32612. button.style.width = "150px";
  32613. button.style.marginBottom = "5px";
  32614. button.style.color = "#444444";
  32615. button.style.border = "1px solid white";
  32616. button.className = "debugLayerButton";
  32617. button.addEventListener("click", function (evt) {
  32618. task(evt.target, tag);
  32619. });
  32620. root.appendChild(button);
  32621. root.appendChild(document.createElement("br"));
  32622. };
  32623. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  32624. if (tag === void 0) { tag = null; }
  32625. var label = document.createElement("label");
  32626. label.style.display = "inline";
  32627. var boundingBoxesRadio = document.createElement("input");
  32628. boundingBoxesRadio.type = "radio";
  32629. boundingBoxesRadio.name = name;
  32630. boundingBoxesRadio.checked = initialState;
  32631. boundingBoxesRadio.style.display = "inline";
  32632. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  32633. boundingBoxesRadio.style.verticalAlign = "sub";
  32634. boundingBoxesRadio.addEventListener("change", function (evt) {
  32635. task(evt.target, tag);
  32636. });
  32637. label.appendChild(boundingBoxesRadio);
  32638. label.appendChild(document.createTextNode(title));
  32639. root.appendChild(label);
  32640. root.appendChild(document.createElement("br"));
  32641. };
  32642. DebugLayer.prototype._generateDOMelements = function () {
  32643. var _this = this;
  32644. this._globalDiv.id = "DebugLayer";
  32645. this._globalDiv.style.position = "absolute";
  32646. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  32647. this._globalDiv.style.fontSize = "14px";
  32648. this._globalDiv.style.color = "white";
  32649. // Drawing canvas
  32650. this._drawingCanvas = document.createElement("canvas");
  32651. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  32652. this._drawingCanvas.style.position = "absolute";
  32653. this._drawingCanvas.style.pointerEvents = "none";
  32654. this._drawingCanvas.style.backgroundColor = "transparent";
  32655. this._drawingContext = this._drawingCanvas.getContext("2d");
  32656. this._globalDiv.appendChild(this._drawingCanvas);
  32657. if (this._showUI) {
  32658. var background = "rgba(128, 128, 128, 0.4)";
  32659. var border = "rgb(180, 180, 180) solid 1px";
  32660. // Stats
  32661. this._statsDiv = document.createElement("div");
  32662. this._statsDiv.id = "DebugLayerStats";
  32663. this._statsDiv.style.border = border;
  32664. this._statsDiv.style.position = "absolute";
  32665. this._statsDiv.style.background = background;
  32666. this._statsDiv.style.padding = "0px 0px 0px 5px";
  32667. this._generateheader(this._statsDiv, "STATISTICS");
  32668. this._statsSubsetDiv = document.createElement("div");
  32669. this._statsSubsetDiv.style.paddingTop = "5px";
  32670. this._statsSubsetDiv.style.paddingBottom = "5px";
  32671. this._statsSubsetDiv.style.overflowY = "auto";
  32672. this._statsDiv.appendChild(this._statsSubsetDiv);
  32673. // Tree
  32674. this._treeDiv = document.createElement("div");
  32675. this._treeDiv.id = "DebugLayerTree";
  32676. this._treeDiv.style.border = border;
  32677. this._treeDiv.style.position = "absolute";
  32678. this._treeDiv.style.background = background;
  32679. this._treeDiv.style.padding = "0px 0px 0px 5px";
  32680. this._treeDiv.style.display = "none";
  32681. this._generateheader(this._treeDiv, "MESHES TREE");
  32682. this._treeSubsetDiv = document.createElement("div");
  32683. this._treeSubsetDiv.style.paddingTop = "5px";
  32684. this._treeSubsetDiv.style.paddingRight = "5px";
  32685. this._treeSubsetDiv.style.overflowY = "auto";
  32686. this._treeSubsetDiv.style.maxHeight = "300px";
  32687. this._treeDiv.appendChild(this._treeSubsetDiv);
  32688. this._needToRefreshMeshesTree = true;
  32689. // Logs
  32690. this._logDiv = document.createElement("div");
  32691. this._logDiv.style.border = border;
  32692. this._logDiv.id = "DebugLayerLogs";
  32693. this._logDiv.style.position = "absolute";
  32694. this._logDiv.style.background = background;
  32695. this._logDiv.style.padding = "0px 0px 0px 5px";
  32696. this._logDiv.style.display = "none";
  32697. this._generateheader(this._logDiv, "LOGS");
  32698. this._logSubsetDiv = document.createElement("div");
  32699. this._logSubsetDiv.style.height = "127px";
  32700. this._logSubsetDiv.style.paddingTop = "5px";
  32701. this._logSubsetDiv.style.overflowY = "auto";
  32702. this._logSubsetDiv.style.fontSize = "12px";
  32703. this._logSubsetDiv.style.fontFamily = "consolas";
  32704. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  32705. this._logDiv.appendChild(this._logSubsetDiv);
  32706. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  32707. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  32708. };
  32709. // Options
  32710. this._optionsDiv = document.createElement("div");
  32711. this._optionsDiv.id = "DebugLayerOptions";
  32712. this._optionsDiv.style.border = border;
  32713. this._optionsDiv.style.position = "absolute";
  32714. this._optionsDiv.style.background = background;
  32715. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  32716. this._optionsDiv.style.overflowY = "auto";
  32717. this._generateheader(this._optionsDiv, "OPTIONS");
  32718. this._optionsSubsetDiv = document.createElement("div");
  32719. this._optionsSubsetDiv.style.paddingTop = "5px";
  32720. this._optionsSubsetDiv.style.paddingBottom = "5px";
  32721. this._optionsSubsetDiv.style.overflowY = "auto";
  32722. this._optionsSubsetDiv.style.maxHeight = "200px";
  32723. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  32724. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  32725. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  32726. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  32727. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  32728. _this._displayTree = element.checked;
  32729. _this._needToRefreshMeshesTree = true;
  32730. });
  32731. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32732. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  32733. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  32734. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  32735. _this._labelsEnabled = element.checked;
  32736. if (!_this._labelsEnabled) {
  32737. _this._clearLabels();
  32738. }
  32739. });
  32740. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  32741. if (element.checked) {
  32742. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  32743. }
  32744. else {
  32745. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  32746. }
  32747. });
  32748. ;
  32749. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32750. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  32751. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  32752. if (element.checked) {
  32753. _this._scene.forceWireframe = false;
  32754. _this._scene.forcePointsCloud = false;
  32755. }
  32756. });
  32757. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  32758. if (element.checked) {
  32759. _this._scene.forceWireframe = true;
  32760. _this._scene.forcePointsCloud = false;
  32761. }
  32762. });
  32763. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  32764. if (element.checked) {
  32765. _this._scene.forceWireframe = false;
  32766. _this._scene.forcePointsCloud = true;
  32767. }
  32768. });
  32769. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32770. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  32771. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  32772. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  32773. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  32774. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  32775. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  32776. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  32777. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  32778. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  32779. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  32780. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  32781. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32782. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  32783. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  32784. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  32785. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  32786. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  32787. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  32788. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  32789. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  32790. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  32791. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  32792. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  32793. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  32794. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  32795. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  32796. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  32797. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  32798. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32799. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  32800. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  32801. if (element.checked) {
  32802. _this._scene.headphone = true;
  32803. }
  32804. });
  32805. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  32806. if (element.checked) {
  32807. _this._scene.headphone = false;
  32808. }
  32809. });
  32810. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  32811. _this._scene.audioEnabled = !element.checked;
  32812. });
  32813. }
  32814. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32815. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  32816. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  32817. if (!element.checked) {
  32818. _this._clearSkeletonViewers();
  32819. return;
  32820. }
  32821. for (var index = 0; index < _this._scene.meshes.length; index++) {
  32822. var mesh = _this._scene.meshes[index];
  32823. if (mesh.skeleton) {
  32824. var found = false;
  32825. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  32826. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  32827. found = true;
  32828. break;
  32829. }
  32830. }
  32831. if (found) {
  32832. continue;
  32833. }
  32834. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  32835. viewer.isEnabled = true;
  32836. _this._skeletonViewers.push(viewer);
  32837. }
  32838. }
  32839. });
  32840. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32841. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  32842. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  32843. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  32844. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  32845. if (_this._camera) {
  32846. console.log(_this._camera);
  32847. }
  32848. else {
  32849. console.warn("No camera defined, or debug layer created before camera creation!");
  32850. }
  32851. });
  32852. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32853. this._globalDiv.appendChild(this._statsDiv);
  32854. this._globalDiv.appendChild(this._logDiv);
  32855. this._globalDiv.appendChild(this._optionsDiv);
  32856. this._globalDiv.appendChild(this._treeDiv);
  32857. }
  32858. };
  32859. DebugLayer.prototype._displayStats = function () {
  32860. var scene = this._scene;
  32861. var engine = scene.getEngine();
  32862. var glInfo = engine.getGlInfo();
  32863. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  32864. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32865. + "<b>Count</b><br>"
  32866. + "Total meshes: " + scene.meshes.length + "<br>"
  32867. + "Total lights: " + scene.lights.length + "<br>"
  32868. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  32869. + "Total materials: " + scene.materials.length + "<br>"
  32870. + "Total textures: " + scene.textures.length + "<br>"
  32871. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  32872. + "Active indices: " + scene.getActiveIndices() + "<br>"
  32873. + "Active bones: " + scene.getActiveBones() + "<br>"
  32874. + "Active particles: " + scene.getActiveParticles() + "<br>"
  32875. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  32876. + "<b>Duration</b><br>"
  32877. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  32878. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  32879. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  32880. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  32881. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  32882. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  32883. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  32884. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  32885. + "</div>"
  32886. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32887. + "<b>Extensions</b><br>"
  32888. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  32889. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  32890. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  32891. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  32892. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  32893. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  32894. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  32895. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  32896. + "</div><br>"
  32897. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32898. + "<b>Caps.</b><br>"
  32899. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  32900. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  32901. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  32902. + "<b>Info</b><br>"
  32903. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  32904. + glInfo.version + "<br>"
  32905. + "</div><br>"
  32906. + glInfo.renderer + "<br>";
  32907. if (this.customStatsFunction) {
  32908. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  32909. }
  32910. };
  32911. return DebugLayer;
  32912. })();
  32913. BABYLON.DebugLayer = DebugLayer;
  32914. })(BABYLON || (BABYLON = {}));
  32915. var BABYLON;
  32916. (function (BABYLON) {
  32917. var DefaultLoadingScreen = (function () {
  32918. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  32919. var _this = this;
  32920. if (_loadingText === void 0) { _loadingText = ""; }
  32921. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  32922. this._renderingCanvas = _renderingCanvas;
  32923. this._loadingText = _loadingText;
  32924. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  32925. // Resize
  32926. this._resizeLoadingUI = function () {
  32927. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  32928. _this._loadingDiv.style.position = "absolute";
  32929. _this._loadingDiv.style.left = canvasRect.left + "px";
  32930. _this._loadingDiv.style.top = canvasRect.top + "px";
  32931. _this._loadingDiv.style.width = canvasRect.width + "px";
  32932. _this._loadingDiv.style.height = canvasRect.height + "px";
  32933. };
  32934. }
  32935. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  32936. var _this = this;
  32937. if (this._loadingDiv) {
  32938. // Do not add a loading screen if there is already one
  32939. return;
  32940. }
  32941. this._loadingDiv = document.createElement("div");
  32942. this._loadingDiv.id = "babylonjsLoadingDiv";
  32943. this._loadingDiv.style.opacity = "0";
  32944. this._loadingDiv.style.transition = "opacity 1.5s ease";
  32945. // Loading text
  32946. this._loadingTextDiv = document.createElement("div");
  32947. this._loadingTextDiv.style.position = "absolute";
  32948. this._loadingTextDiv.style.left = "0";
  32949. this._loadingTextDiv.style.top = "50%";
  32950. this._loadingTextDiv.style.marginTop = "80px";
  32951. this._loadingTextDiv.style.width = "100%";
  32952. this._loadingTextDiv.style.height = "20px";
  32953. this._loadingTextDiv.style.fontFamily = "Arial";
  32954. this._loadingTextDiv.style.fontSize = "14px";
  32955. this._loadingTextDiv.style.color = "white";
  32956. this._loadingTextDiv.style.textAlign = "center";
  32957. this._loadingTextDiv.innerHTML = "Loading";
  32958. this._loadingDiv.appendChild(this._loadingTextDiv);
  32959. //set the predefined text
  32960. this._loadingTextDiv.innerHTML = this._loadingText;
  32961. // Loading img
  32962. var imgBack = new Image();
  32963. 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==";
  32964. imgBack.style.position = "absolute";
  32965. imgBack.style.left = "50%";
  32966. imgBack.style.top = "50%";
  32967. imgBack.style.marginLeft = "-50px";
  32968. imgBack.style.marginTop = "-50px";
  32969. imgBack.style.transition = "transform 1.0s ease";
  32970. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  32971. var deg = 360;
  32972. var onTransitionEnd = function () {
  32973. deg += 360;
  32974. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  32975. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  32976. };
  32977. imgBack.addEventListener("transitionend", onTransitionEnd);
  32978. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  32979. this._loadingDiv.appendChild(imgBack);
  32980. // front image
  32981. var imgFront = new Image();
  32982. 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=";
  32983. imgFront.style.position = "absolute";
  32984. imgFront.style.left = "50%";
  32985. imgFront.style.top = "50%";
  32986. imgFront.style.marginLeft = "-50px";
  32987. imgFront.style.marginTop = "-50px";
  32988. this._loadingDiv.appendChild(imgFront);
  32989. this._resizeLoadingUI();
  32990. window.addEventListener("resize", this._resizeLoadingUI);
  32991. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32992. document.body.appendChild(this._loadingDiv);
  32993. setTimeout(function () {
  32994. _this._loadingDiv.style.opacity = "1";
  32995. imgBack.style.transform = "rotateZ(360deg)";
  32996. imgBack.style.webkitTransform = "rotateZ(360deg)";
  32997. }, 0);
  32998. };
  32999. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33000. var _this = this;
  33001. if (!this._loadingDiv) {
  33002. return;
  33003. }
  33004. var onTransitionEnd = function () {
  33005. if (!_this._loadingDiv) {
  33006. return;
  33007. }
  33008. document.body.removeChild(_this._loadingDiv);
  33009. window.removeEventListener("resize", _this._resizeLoadingUI);
  33010. _this._loadingDiv = null;
  33011. };
  33012. this._loadingDiv.style.opacity = "0";
  33013. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33014. };
  33015. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33016. set: function (text) {
  33017. this._loadingText = text;
  33018. if (this._loadingTextDiv) {
  33019. this._loadingTextDiv.innerHTML = this._loadingText;
  33020. }
  33021. },
  33022. enumerable: true,
  33023. configurable: true
  33024. });
  33025. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33026. get: function () {
  33027. return this._loadingDivBackgroundColor;
  33028. },
  33029. set: function (color) {
  33030. this._loadingDivBackgroundColor = color;
  33031. if (!this._loadingDiv) {
  33032. return;
  33033. }
  33034. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33035. },
  33036. enumerable: true,
  33037. configurable: true
  33038. });
  33039. return DefaultLoadingScreen;
  33040. })();
  33041. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33042. })(BABYLON || (BABYLON = {}));
  33043. var BABYLON;
  33044. (function (BABYLON) {
  33045. var AudioEngine = (function () {
  33046. function AudioEngine() {
  33047. this._audioContext = null;
  33048. this._audioContextInitialized = false;
  33049. this.canUseWebAudio = false;
  33050. this.WarnedWebAudioUnsupported = false;
  33051. this.unlocked = false;
  33052. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33053. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33054. this.canUseWebAudio = true;
  33055. }
  33056. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33057. this._unlockiOSaudio();
  33058. }
  33059. else {
  33060. this.unlocked = true;
  33061. }
  33062. }
  33063. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33064. get: function () {
  33065. if (!this._audioContextInitialized) {
  33066. this._initializeAudioContext();
  33067. }
  33068. return this._audioContext;
  33069. },
  33070. enumerable: true,
  33071. configurable: true
  33072. });
  33073. AudioEngine.prototype._unlockiOSaudio = function () {
  33074. var _this = this;
  33075. var unlockaudio = function () {
  33076. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33077. var source = _this.audioContext.createBufferSource();
  33078. source.buffer = buffer;
  33079. source.connect(_this.audioContext.destination);
  33080. source.start(0);
  33081. setTimeout(function () {
  33082. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33083. _this.unlocked = true;
  33084. window.removeEventListener('touchend', unlockaudio, false);
  33085. if (_this.onAudioUnlocked) {
  33086. _this.onAudioUnlocked();
  33087. }
  33088. }
  33089. }, 0);
  33090. };
  33091. window.addEventListener('touchend', unlockaudio, false);
  33092. };
  33093. AudioEngine.prototype._initializeAudioContext = function () {
  33094. try {
  33095. if (this.canUseWebAudio) {
  33096. this._audioContext = new AudioContext();
  33097. // create a global volume gain node
  33098. this.masterGain = this._audioContext.createGain();
  33099. this.masterGain.gain.value = 1;
  33100. this.masterGain.connect(this._audioContext.destination);
  33101. this._audioContextInitialized = true;
  33102. }
  33103. }
  33104. catch (e) {
  33105. this.canUseWebAudio = false;
  33106. BABYLON.Tools.Error("Web Audio: " + e.message);
  33107. }
  33108. };
  33109. AudioEngine.prototype.dispose = function () {
  33110. if (this.canUseWebAudio && this._audioContextInitialized) {
  33111. if (this._connectedAnalyser) {
  33112. this._connectedAnalyser.stopDebugCanvas();
  33113. this._connectedAnalyser.dispose();
  33114. this.masterGain.disconnect();
  33115. this.masterGain.connect(this._audioContext.destination);
  33116. this._connectedAnalyser = null;
  33117. }
  33118. this.masterGain.gain.value = 1;
  33119. }
  33120. this.WarnedWebAudioUnsupported = false;
  33121. };
  33122. AudioEngine.prototype.getGlobalVolume = function () {
  33123. if (this.canUseWebAudio && this._audioContextInitialized) {
  33124. return this.masterGain.gain.value;
  33125. }
  33126. else {
  33127. return -1;
  33128. }
  33129. };
  33130. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33131. if (this.canUseWebAudio && this._audioContextInitialized) {
  33132. this.masterGain.gain.value = newVolume;
  33133. }
  33134. };
  33135. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33136. if (this._connectedAnalyser) {
  33137. this._connectedAnalyser.stopDebugCanvas();
  33138. }
  33139. if (this.canUseWebAudio && this._audioContextInitialized) {
  33140. this._connectedAnalyser = analyser;
  33141. this.masterGain.disconnect();
  33142. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33143. }
  33144. };
  33145. return AudioEngine;
  33146. })();
  33147. BABYLON.AudioEngine = AudioEngine;
  33148. })(BABYLON || (BABYLON = {}));
  33149. var BABYLON;
  33150. (function (BABYLON) {
  33151. var Sound = (function () {
  33152. /**
  33153. * Create a sound and attach it to a scene
  33154. * @param name Name of your sound
  33155. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33156. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33157. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33158. */
  33159. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33160. var _this = this;
  33161. this.autoplay = false;
  33162. this.loop = false;
  33163. this.useCustomAttenuation = false;
  33164. this.spatialSound = false;
  33165. this.refDistance = 1;
  33166. this.rolloffFactor = 1;
  33167. this.maxDistance = 100;
  33168. this.distanceModel = "linear";
  33169. this._panningModel = "equalpower";
  33170. this._playbackRate = 1;
  33171. this._streaming = false;
  33172. this._startTime = 0;
  33173. this._startOffset = 0;
  33174. this._position = BABYLON.Vector3.Zero();
  33175. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33176. this._volume = 1;
  33177. this._isLoaded = false;
  33178. this._isReadyToPlay = false;
  33179. this.isPlaying = false;
  33180. this.isPaused = false;
  33181. this._isDirectional = false;
  33182. // Used if you'd like to create a directional sound.
  33183. // If not set, the sound will be omnidirectional
  33184. this._coneInnerAngle = 360;
  33185. this._coneOuterAngle = 360;
  33186. this._coneOuterGain = 0;
  33187. this._isOutputConnected = false;
  33188. this.name = name;
  33189. this._scene = scene;
  33190. this._readyToPlayCallback = readyToPlayCallback;
  33191. // Default custom attenuation function is a linear attenuation
  33192. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33193. if (currentDistance < maxDistance) {
  33194. return currentVolume * (1 - currentDistance / maxDistance);
  33195. }
  33196. else {
  33197. return 0;
  33198. }
  33199. };
  33200. if (options) {
  33201. this.autoplay = options.autoplay || false;
  33202. this.loop = options.loop || false;
  33203. // if volume === 0, we need another way to check this option
  33204. if (options.volume !== undefined) {
  33205. this._volume = options.volume;
  33206. }
  33207. this.spatialSound = options.spatialSound || false;
  33208. this.maxDistance = options.maxDistance || 100;
  33209. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33210. this.rolloffFactor = options.rolloffFactor || 1;
  33211. this.refDistance = options.refDistance || 1;
  33212. this.distanceModel = options.distanceModel || "linear";
  33213. this._playbackRate = options.playbackRate || 1;
  33214. this._streaming = options.streaming || false;
  33215. }
  33216. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33217. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33218. this._soundGain.gain.value = this._volume;
  33219. this._inputAudioNode = this._soundGain;
  33220. this._ouputAudioNode = this._soundGain;
  33221. if (this.spatialSound) {
  33222. this._createSpatialParameters();
  33223. }
  33224. this._scene.mainSoundTrack.AddSound(this);
  33225. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33226. if (urlOrArrayBuffer) {
  33227. // If it's an URL
  33228. if (typeof (urlOrArrayBuffer) === "string") {
  33229. // Loading sound using XHR2
  33230. if (!this._streaming) {
  33231. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33232. }
  33233. else {
  33234. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33235. this._htmlAudioElement.controls = false;
  33236. this._htmlAudioElement.loop = this.loop;
  33237. this._htmlAudioElement.crossOrigin = "anonymous";
  33238. this._htmlAudioElement.preload = "auto";
  33239. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33240. _this._isReadyToPlay = true;
  33241. if (_this.autoplay) {
  33242. _this.play();
  33243. }
  33244. if (_this._readyToPlayCallback) {
  33245. _this._readyToPlayCallback();
  33246. }
  33247. });
  33248. document.body.appendChild(this._htmlAudioElement);
  33249. }
  33250. }
  33251. else {
  33252. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33253. if (urlOrArrayBuffer.byteLength > 0) {
  33254. this._soundLoaded(urlOrArrayBuffer);
  33255. }
  33256. }
  33257. else {
  33258. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33259. }
  33260. }
  33261. }
  33262. }
  33263. else {
  33264. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33265. this._scene.mainSoundTrack.AddSound(this);
  33266. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33267. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33268. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33269. }
  33270. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33271. if (this._readyToPlayCallback) {
  33272. window.setTimeout(function () {
  33273. _this._readyToPlayCallback();
  33274. }, 1000);
  33275. }
  33276. }
  33277. }
  33278. Sound.prototype.dispose = function () {
  33279. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33280. if (this.isPlaying) {
  33281. this.stop();
  33282. }
  33283. this._isReadyToPlay = false;
  33284. if (this.soundTrackId === -1) {
  33285. this._scene.mainSoundTrack.RemoveSound(this);
  33286. }
  33287. else {
  33288. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33289. }
  33290. if (this._soundGain) {
  33291. this._soundGain.disconnect();
  33292. this._soundGain = null;
  33293. }
  33294. if (this._soundPanner) {
  33295. this._soundPanner.disconnect();
  33296. this._soundPanner = null;
  33297. }
  33298. if (this._soundSource) {
  33299. this._soundSource.disconnect();
  33300. this._soundSource = null;
  33301. }
  33302. this._audioBuffer = null;
  33303. if (this._htmlAudioElement) {
  33304. this._htmlAudioElement.pause();
  33305. this._htmlAudioElement.src = "";
  33306. document.body.removeChild(this._htmlAudioElement);
  33307. }
  33308. if (this._connectedMesh) {
  33309. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33310. this._connectedMesh = null;
  33311. }
  33312. }
  33313. };
  33314. Sound.prototype._soundLoaded = function (audioData) {
  33315. var _this = this;
  33316. this._isLoaded = true;
  33317. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33318. _this._audioBuffer = buffer;
  33319. _this._isReadyToPlay = true;
  33320. if (_this.autoplay) {
  33321. _this.play();
  33322. }
  33323. if (_this._readyToPlayCallback) {
  33324. _this._readyToPlayCallback();
  33325. }
  33326. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33327. };
  33328. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33329. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33330. this._audioBuffer = audioBuffer;
  33331. this._isReadyToPlay = true;
  33332. }
  33333. };
  33334. Sound.prototype.updateOptions = function (options) {
  33335. if (options) {
  33336. this.loop = options.loop || this.loop;
  33337. this.maxDistance = options.maxDistance || this.maxDistance;
  33338. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33339. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33340. this.refDistance = options.refDistance || this.refDistance;
  33341. this.distanceModel = options.distanceModel || this.distanceModel;
  33342. this._playbackRate = options.playbackRate || this._playbackRate;
  33343. this._updateSpatialParameters();
  33344. if (this.isPlaying) {
  33345. if (this._streaming) {
  33346. this._htmlAudioElement.playbackRate = this._playbackRate;
  33347. }
  33348. else {
  33349. this._soundSource.playbackRate.value = this._playbackRate;
  33350. }
  33351. }
  33352. }
  33353. };
  33354. Sound.prototype._createSpatialParameters = function () {
  33355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33356. if (this._scene.headphone) {
  33357. this._panningModel = "HRTF";
  33358. }
  33359. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33360. this._updateSpatialParameters();
  33361. this._soundPanner.connect(this._ouputAudioNode);
  33362. this._inputAudioNode = this._soundPanner;
  33363. }
  33364. };
  33365. Sound.prototype._updateSpatialParameters = function () {
  33366. if (this.spatialSound) {
  33367. if (this.useCustomAttenuation) {
  33368. // Tricks to disable in a way embedded Web Audio attenuation
  33369. this._soundPanner.distanceModel = "linear";
  33370. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33371. this._soundPanner.refDistance = 1;
  33372. this._soundPanner.rolloffFactor = 1;
  33373. this._soundPanner.panningModel = this._panningModel;
  33374. }
  33375. else {
  33376. this._soundPanner.distanceModel = this.distanceModel;
  33377. this._soundPanner.maxDistance = this.maxDistance;
  33378. this._soundPanner.refDistance = this.refDistance;
  33379. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33380. this._soundPanner.panningModel = this._panningModel;
  33381. }
  33382. }
  33383. };
  33384. Sound.prototype.switchPanningModelToHRTF = function () {
  33385. this._panningModel = "HRTF";
  33386. this._switchPanningModel();
  33387. };
  33388. Sound.prototype.switchPanningModelToEqualPower = function () {
  33389. this._panningModel = "equalpower";
  33390. this._switchPanningModel();
  33391. };
  33392. Sound.prototype._switchPanningModel = function () {
  33393. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33394. this._soundPanner.panningModel = this._panningModel;
  33395. }
  33396. };
  33397. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33399. if (this._isOutputConnected) {
  33400. this._ouputAudioNode.disconnect();
  33401. }
  33402. this._ouputAudioNode.connect(soundTrackAudioNode);
  33403. this._isOutputConnected = true;
  33404. }
  33405. };
  33406. /**
  33407. * Transform this sound into a directional source
  33408. * @param coneInnerAngle Size of the inner cone in degree
  33409. * @param coneOuterAngle Size of the outer cone in degree
  33410. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33411. */
  33412. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33413. if (coneOuterAngle < coneInnerAngle) {
  33414. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33415. return;
  33416. }
  33417. this._coneInnerAngle = coneInnerAngle;
  33418. this._coneOuterAngle = coneOuterAngle;
  33419. this._coneOuterGain = coneOuterGain;
  33420. this._isDirectional = true;
  33421. if (this.isPlaying && this.loop) {
  33422. this.stop();
  33423. this.play();
  33424. }
  33425. };
  33426. Sound.prototype.setPosition = function (newPosition) {
  33427. this._position = newPosition;
  33428. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33429. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33430. }
  33431. };
  33432. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33433. this._localDirection = newLocalDirection;
  33434. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33435. this._updateDirection();
  33436. }
  33437. };
  33438. Sound.prototype._updateDirection = function () {
  33439. var mat = this._connectedMesh.getWorldMatrix();
  33440. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33441. direction.normalize();
  33442. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33443. };
  33444. Sound.prototype.updateDistanceFromListener = function () {
  33445. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33446. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33447. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33448. }
  33449. };
  33450. Sound.prototype.setAttenuationFunction = function (callback) {
  33451. this._customAttenuationFunction = callback;
  33452. };
  33453. /**
  33454. * Play the sound
  33455. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33456. */
  33457. Sound.prototype.play = function (time) {
  33458. var _this = this;
  33459. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33460. try {
  33461. if (this._startOffset < 0) {
  33462. time = -this._startOffset;
  33463. this._startOffset = 0;
  33464. }
  33465. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33466. if (!this._soundSource || !this._streamingSource) {
  33467. if (this.spatialSound) {
  33468. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33469. if (this._isDirectional) {
  33470. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33471. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33472. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33473. if (this._connectedMesh) {
  33474. this._updateDirection();
  33475. }
  33476. else {
  33477. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33478. }
  33479. }
  33480. }
  33481. }
  33482. if (this._streaming) {
  33483. if (!this._streamingSource) {
  33484. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33485. this._htmlAudioElement.onended = function () { _this._onended(); };
  33486. this._htmlAudioElement.playbackRate = this._playbackRate;
  33487. }
  33488. this._streamingSource.disconnect();
  33489. this._streamingSource.connect(this._inputAudioNode);
  33490. this._htmlAudioElement.play();
  33491. }
  33492. else {
  33493. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33494. this._soundSource.buffer = this._audioBuffer;
  33495. this._soundSource.connect(this._inputAudioNode);
  33496. this._soundSource.loop = this.loop;
  33497. this._soundSource.playbackRate.value = this._playbackRate;
  33498. this._soundSource.onended = function () { _this._onended(); };
  33499. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33500. }
  33501. this._startTime = startTime;
  33502. this.isPlaying = true;
  33503. this.isPaused = false;
  33504. }
  33505. catch (ex) {
  33506. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33507. }
  33508. }
  33509. };
  33510. Sound.prototype._onended = function () {
  33511. this.isPlaying = false;
  33512. if (this.onended) {
  33513. this.onended();
  33514. }
  33515. };
  33516. /**
  33517. * Stop the sound
  33518. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33519. */
  33520. Sound.prototype.stop = function (time) {
  33521. if (this.isPlaying) {
  33522. if (this._streaming) {
  33523. this._htmlAudioElement.pause();
  33524. // Test needed for Firefox or it will generate an Invalid State Error
  33525. if (this._htmlAudioElement.currentTime > 0) {
  33526. this._htmlAudioElement.currentTime = 0;
  33527. }
  33528. }
  33529. else {
  33530. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33531. this._soundSource.stop(stopTime);
  33532. if (!this.isPaused) {
  33533. this._startOffset = 0;
  33534. }
  33535. }
  33536. this.isPlaying = false;
  33537. }
  33538. };
  33539. Sound.prototype.pause = function () {
  33540. if (this.isPlaying) {
  33541. this.isPaused = true;
  33542. if (this._streaming) {
  33543. this._htmlAudioElement.pause();
  33544. }
  33545. else {
  33546. this.stop(0);
  33547. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33548. }
  33549. }
  33550. };
  33551. Sound.prototype.setVolume = function (newVolume, time) {
  33552. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33553. if (time) {
  33554. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33555. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33556. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33557. }
  33558. else {
  33559. this._soundGain.gain.value = newVolume;
  33560. }
  33561. }
  33562. this._volume = newVolume;
  33563. };
  33564. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33565. this._playbackRate = newPlaybackRate;
  33566. if (this.isPlaying) {
  33567. if (this._streaming) {
  33568. this._htmlAudioElement.playbackRate = this._playbackRate;
  33569. }
  33570. else {
  33571. this._soundSource.playbackRate.value = this._playbackRate;
  33572. }
  33573. }
  33574. };
  33575. Sound.prototype.getVolume = function () {
  33576. return this._volume;
  33577. };
  33578. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33579. var _this = this;
  33580. if (this._connectedMesh) {
  33581. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33582. this._registerFunc = null;
  33583. }
  33584. this._connectedMesh = meshToConnectTo;
  33585. if (!this.spatialSound) {
  33586. this.spatialSound = true;
  33587. this._createSpatialParameters();
  33588. if (this.isPlaying && this.loop) {
  33589. this.stop();
  33590. this.play();
  33591. }
  33592. }
  33593. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33594. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33595. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33596. };
  33597. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33598. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33599. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33600. this._updateDirection();
  33601. }
  33602. };
  33603. Sound.prototype.clone = function () {
  33604. var _this = this;
  33605. if (!this._streaming) {
  33606. var setBufferAndRun = function () {
  33607. if (_this._isReadyToPlay) {
  33608. clonedSound._audioBuffer = _this.getAudioBuffer();
  33609. clonedSound._isReadyToPlay = true;
  33610. if (clonedSound.autoplay) {
  33611. clonedSound.play();
  33612. }
  33613. }
  33614. else {
  33615. window.setTimeout(setBufferAndRun, 300);
  33616. }
  33617. };
  33618. var currentOptions = {
  33619. autoplay: this.autoplay, loop: this.loop,
  33620. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  33621. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  33622. refDistance: this.refDistance, distanceModel: this.distanceModel
  33623. };
  33624. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  33625. if (this.useCustomAttenuation) {
  33626. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  33627. }
  33628. clonedSound.setPosition(this._position);
  33629. clonedSound.setPlaybackRate(this._playbackRate);
  33630. setBufferAndRun();
  33631. return clonedSound;
  33632. }
  33633. else {
  33634. return null;
  33635. }
  33636. };
  33637. Sound.prototype.getAudioBuffer = function () {
  33638. return this._audioBuffer;
  33639. };
  33640. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  33641. var soundName = parsedSound.name;
  33642. var soundUrl;
  33643. if (parsedSound.url) {
  33644. soundUrl = rootUrl + parsedSound.url;
  33645. }
  33646. else {
  33647. soundUrl = rootUrl + soundName;
  33648. }
  33649. var options = {
  33650. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33651. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33652. rolloffFactor: parsedSound.rolloffFactor,
  33653. refDistance: parsedSound.refDistance,
  33654. distanceModel: parsedSound.distanceModel,
  33655. playbackRate: parsedSound.playbackRate
  33656. };
  33657. var newSound;
  33658. if (!sourceSound) {
  33659. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33660. scene._addPendingData(newSound);
  33661. }
  33662. else {
  33663. var setBufferAndRun = function () {
  33664. if (sourceSound._isReadyToPlay) {
  33665. newSound._audioBuffer = sourceSound.getAudioBuffer();
  33666. newSound._isReadyToPlay = true;
  33667. if (newSound.autoplay) {
  33668. newSound.play();
  33669. }
  33670. }
  33671. else {
  33672. window.setTimeout(setBufferAndRun, 300);
  33673. }
  33674. };
  33675. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  33676. setBufferAndRun();
  33677. }
  33678. if (parsedSound.position) {
  33679. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33680. newSound.setPosition(soundPosition);
  33681. }
  33682. if (parsedSound.isDirectional) {
  33683. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33684. if (parsedSound.localDirectionToMesh) {
  33685. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33686. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33687. }
  33688. }
  33689. if (parsedSound.connectedMeshId) {
  33690. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33691. if (connectedMesh) {
  33692. newSound.attachToMesh(connectedMesh);
  33693. }
  33694. }
  33695. return newSound;
  33696. };
  33697. return Sound;
  33698. })();
  33699. BABYLON.Sound = Sound;
  33700. })(BABYLON || (BABYLON = {}));
  33701. var BABYLON;
  33702. (function (BABYLON) {
  33703. var SoundTrack = (function () {
  33704. function SoundTrack(scene, options) {
  33705. this.id = -1;
  33706. this._isMainTrack = false;
  33707. this._isInitialized = false;
  33708. this._scene = scene;
  33709. this.soundCollection = new Array();
  33710. this._options = options;
  33711. if (!this._isMainTrack) {
  33712. this._scene.soundTracks.push(this);
  33713. this.id = this._scene.soundTracks.length - 1;
  33714. }
  33715. }
  33716. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33717. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33718. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33719. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33720. if (this._options) {
  33721. if (this._options.volume) {
  33722. this._outputAudioNode.gain.value = this._options.volume;
  33723. }
  33724. if (this._options.mainTrack) {
  33725. this._isMainTrack = this._options.mainTrack;
  33726. }
  33727. }
  33728. this._isInitialized = true;
  33729. }
  33730. };
  33731. SoundTrack.prototype.dispose = function () {
  33732. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33733. if (this._connectedAnalyser) {
  33734. this._connectedAnalyser.stopDebugCanvas();
  33735. }
  33736. while (this.soundCollection.length) {
  33737. this.soundCollection[0].dispose();
  33738. }
  33739. if (this._outputAudioNode) {
  33740. this._outputAudioNode.disconnect();
  33741. }
  33742. this._outputAudioNode = null;
  33743. }
  33744. };
  33745. SoundTrack.prototype.AddSound = function (sound) {
  33746. if (!this._isInitialized) {
  33747. this._initializeSoundTrackAudioGraph();
  33748. }
  33749. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33750. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33751. }
  33752. if (sound.soundTrackId) {
  33753. if (sound.soundTrackId === -1) {
  33754. this._scene.mainSoundTrack.RemoveSound(sound);
  33755. }
  33756. else {
  33757. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33758. }
  33759. }
  33760. this.soundCollection.push(sound);
  33761. sound.soundTrackId = this.id;
  33762. };
  33763. SoundTrack.prototype.RemoveSound = function (sound) {
  33764. var index = this.soundCollection.indexOf(sound);
  33765. if (index !== -1) {
  33766. this.soundCollection.splice(index, 1);
  33767. }
  33768. };
  33769. SoundTrack.prototype.setVolume = function (newVolume) {
  33770. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33771. this._outputAudioNode.gain.value = newVolume;
  33772. }
  33773. };
  33774. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33775. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33776. for (var i = 0; i < this.soundCollection.length; i++) {
  33777. this.soundCollection[i].switchPanningModelToHRTF();
  33778. }
  33779. }
  33780. };
  33781. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33782. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33783. for (var i = 0; i < this.soundCollection.length; i++) {
  33784. this.soundCollection[i].switchPanningModelToEqualPower();
  33785. }
  33786. }
  33787. };
  33788. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33789. if (this._connectedAnalyser) {
  33790. this._connectedAnalyser.stopDebugCanvas();
  33791. }
  33792. this._connectedAnalyser = analyser;
  33793. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33794. this._outputAudioNode.disconnect();
  33795. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33796. }
  33797. };
  33798. return SoundTrack;
  33799. })();
  33800. BABYLON.SoundTrack = SoundTrack;
  33801. })(BABYLON || (BABYLON = {}));
  33802. var BABYLON;
  33803. (function (BABYLON) {
  33804. var SIMDVector3 = (function () {
  33805. function SIMDVector3() {
  33806. }
  33807. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  33808. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  33809. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33810. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33811. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33812. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33813. 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));
  33814. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33815. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33816. };
  33817. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  33818. var v0 = SIMD.float32x4.splat(x);
  33819. var v1 = SIMD.float32x4.splat(y);
  33820. var v2 = SIMD.float32x4.splat(z);
  33821. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33822. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33823. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33824. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33825. 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));
  33826. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33827. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33828. };
  33829. return SIMDVector3;
  33830. })();
  33831. BABYLON.SIMDVector3 = SIMDVector3;
  33832. var SIMDMatrix = (function () {
  33833. function SIMDMatrix() {
  33834. }
  33835. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  33836. if (offset === void 0) { offset = 0; }
  33837. var tm = this.m;
  33838. var om = other.m;
  33839. var om0 = SIMD.float32x4.load(om, 0);
  33840. var om1 = SIMD.float32x4.load(om, 4);
  33841. var om2 = SIMD.float32x4.load(om, 8);
  33842. var om3 = SIMD.float32x4.load(om, 12);
  33843. var tm0 = SIMD.float32x4.load(tm, 0);
  33844. 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)))));
  33845. var tm1 = SIMD.float32x4.load(tm, 4);
  33846. 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)))));
  33847. var tm2 = SIMD.float32x4.load(tm, 8);
  33848. 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)))));
  33849. var tm3 = SIMD.float32x4.load(tm, 12);
  33850. 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)))));
  33851. };
  33852. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  33853. var src = this.m;
  33854. var dest = other.m;
  33855. var row0, row1, row2, row3;
  33856. var tmp1;
  33857. var minor0, minor1, minor2, minor3;
  33858. var det;
  33859. // Load the 4 rows
  33860. var src0 = SIMD.float32x4.load(src, 0);
  33861. var src1 = SIMD.float32x4.load(src, 4);
  33862. var src2 = SIMD.float32x4.load(src, 8);
  33863. var src3 = SIMD.float32x4.load(src, 12);
  33864. // Transpose the source matrix. Sort of. Not a true transpose operation
  33865. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33866. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33867. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  33868. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  33869. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33870. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33871. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  33872. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  33873. // This is a true transposition, but it will lead to an incorrect result
  33874. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33875. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33876. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33877. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33878. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33879. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33880. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33881. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33882. // ----
  33883. tmp1 = SIMD.float32x4.mul(row2, row3);
  33884. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33885. minor0 = SIMD.float32x4.mul(row1, tmp1);
  33886. minor1 = SIMD.float32x4.mul(row0, tmp1);
  33887. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33888. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  33889. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  33890. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  33891. // ----
  33892. tmp1 = SIMD.float32x4.mul(row1, row2);
  33893. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33894. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  33895. minor3 = SIMD.float32x4.mul(row0, tmp1);
  33896. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33897. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  33898. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  33899. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  33900. // ----
  33901. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  33902. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33903. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  33904. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  33905. minor2 = SIMD.float32x4.mul(row0, tmp1);
  33906. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33907. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  33908. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  33909. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  33910. // ----
  33911. tmp1 = SIMD.float32x4.mul(row0, row1);
  33912. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33913. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  33914. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  33915. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33916. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  33917. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  33918. // ----
  33919. tmp1 = SIMD.float32x4.mul(row0, row3);
  33920. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33921. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  33922. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  33923. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33924. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  33925. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  33926. // ----
  33927. tmp1 = SIMD.float32x4.mul(row0, row2);
  33928. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33929. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  33930. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  33931. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33932. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  33933. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  33934. // Compute determinant
  33935. det = SIMD.float32x4.mul(row0, minor0);
  33936. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  33937. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  33938. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  33939. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  33940. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  33941. // These shuffles aren't necessary if the faulty transposition is done
  33942. // up at the top of this function.
  33943. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  33944. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  33945. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  33946. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  33947. // Compute final values by multiplying with 1/det
  33948. minor0 = SIMD.float32x4.mul(det, minor0);
  33949. minor1 = SIMD.float32x4.mul(det, minor1);
  33950. minor2 = SIMD.float32x4.mul(det, minor2);
  33951. minor3 = SIMD.float32x4.mul(det, minor3);
  33952. SIMD.float32x4.store(dest, 0, minor0);
  33953. SIMD.float32x4.store(dest, 4, minor1);
  33954. SIMD.float32x4.store(dest, 8, minor2);
  33955. SIMD.float32x4.store(dest, 12, minor3);
  33956. return this;
  33957. };
  33958. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  33959. var out = result.m;
  33960. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  33961. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  33962. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  33963. // cc.kmVec3Subtract(f, pCenter, pEye);
  33964. var f = SIMD.float32x4.sub(center, eye);
  33965. // cc.kmVec3Normalize(f, f);
  33966. var tmp = SIMD.float32x4.mul(f, f);
  33967. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33968. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33969. // cc.kmVec3Assign(up, pUp);
  33970. // cc.kmVec3Normalize(up, up);
  33971. tmp = SIMD.float32x4.mul(up, up);
  33972. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33973. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33974. // cc.kmVec3Cross(s, f, up);
  33975. 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)));
  33976. // cc.kmVec3Normalize(s, s);
  33977. tmp = SIMD.float32x4.mul(s, s);
  33978. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33979. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33980. // cc.kmVec3Cross(u, s, f);
  33981. 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)));
  33982. // cc.kmVec3Normalize(s, s);
  33983. tmp = SIMD.float32x4.mul(s, s);
  33984. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33985. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33986. var zero = SIMD.float32x4.splat(0.0);
  33987. s = SIMD.float32x4.neg(s);
  33988. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  33989. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  33990. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33991. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  33992. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  33993. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  33994. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33995. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  33996. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  33997. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  33998. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  33999. var b3 = SIMD.float32x4.neg(eye);
  34000. b3 = SIMD.float32x4.withW(b3, 1.0);
  34001. 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)))));
  34002. 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)))));
  34003. 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)))));
  34004. 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)))));
  34005. };
  34006. return SIMDMatrix;
  34007. })();
  34008. BABYLON.SIMDMatrix = SIMDMatrix;
  34009. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34010. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34011. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34012. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34013. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34014. var SIMDHelper = (function () {
  34015. function SIMDHelper() {
  34016. }
  34017. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34018. get: function () {
  34019. return SIMDHelper._isEnabled;
  34020. },
  34021. enumerable: true,
  34022. configurable: true
  34023. });
  34024. SIMDHelper.DisableSIMD = function () {
  34025. // Replace functions
  34026. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34027. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34028. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34029. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34030. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34031. SIMDHelper._isEnabled = false;
  34032. };
  34033. SIMDHelper.EnableSIMD = function () {
  34034. if (window.SIMD === undefined) {
  34035. return;
  34036. }
  34037. // Replace functions
  34038. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34039. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34040. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34041. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34042. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34043. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34044. get: function () { return this._data[0]; },
  34045. set: function (value) {
  34046. if (!this._data) {
  34047. this._data = new Float32Array(3);
  34048. }
  34049. this._data[0] = value;
  34050. }
  34051. });
  34052. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34053. get: function () { return this._data[1]; },
  34054. set: function (value) {
  34055. this._data[1] = value;
  34056. }
  34057. });
  34058. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34059. get: function () { return this._data[2]; },
  34060. set: function (value) {
  34061. this._data[2] = value;
  34062. }
  34063. });
  34064. SIMDHelper._isEnabled = true;
  34065. };
  34066. SIMDHelper._isEnabled = false;
  34067. return SIMDHelper;
  34068. })();
  34069. BABYLON.SIMDHelper = SIMDHelper;
  34070. })(BABYLON || (BABYLON = {}));
  34071. var BABYLON;
  34072. (function (BABYLON) {
  34073. var ShaderMaterial = (function (_super) {
  34074. __extends(ShaderMaterial, _super);
  34075. function ShaderMaterial(name, scene, shaderPath, options) {
  34076. _super.call(this, name, scene);
  34077. this._textures = {};
  34078. this._floats = {};
  34079. this._floatsArrays = {};
  34080. this._colors3 = {};
  34081. this._colors4 = {};
  34082. this._vectors2 = {};
  34083. this._vectors3 = {};
  34084. this._vectors4 = {};
  34085. this._matrices = {};
  34086. this._matrices3x3 = {};
  34087. this._matrices2x2 = {};
  34088. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  34089. this._shaderPath = shaderPath;
  34090. options.needAlphaBlending = options.needAlphaBlending || false;
  34091. options.needAlphaTesting = options.needAlphaTesting || false;
  34092. options.attributes = options.attributes || ["position", "normal", "uv"];
  34093. options.uniforms = options.uniforms || ["worldViewProjection"];
  34094. options.samplers = options.samplers || [];
  34095. options.defines = options.defines || [];
  34096. this._options = options;
  34097. }
  34098. ShaderMaterial.prototype.needAlphaBlending = function () {
  34099. return this._options.needAlphaBlending;
  34100. };
  34101. ShaderMaterial.prototype.needAlphaTesting = function () {
  34102. return this._options.needAlphaTesting;
  34103. };
  34104. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  34105. if (this._options.uniforms.indexOf(uniformName) === -1) {
  34106. this._options.uniforms.push(uniformName);
  34107. }
  34108. };
  34109. ShaderMaterial.prototype.setTexture = function (name, texture) {
  34110. if (this._options.samplers.indexOf(name) === -1) {
  34111. this._options.samplers.push(name);
  34112. }
  34113. this._textures[name] = texture;
  34114. return this;
  34115. };
  34116. ShaderMaterial.prototype.setFloat = function (name, value) {
  34117. this._checkUniform(name);
  34118. this._floats[name] = value;
  34119. return this;
  34120. };
  34121. ShaderMaterial.prototype.setFloats = function (name, value) {
  34122. this._checkUniform(name);
  34123. this._floatsArrays[name] = value;
  34124. return this;
  34125. };
  34126. ShaderMaterial.prototype.setColor3 = function (name, value) {
  34127. this._checkUniform(name);
  34128. this._colors3[name] = value;
  34129. return this;
  34130. };
  34131. ShaderMaterial.prototype.setColor4 = function (name, value) {
  34132. this._checkUniform(name);
  34133. this._colors4[name] = value;
  34134. return this;
  34135. };
  34136. ShaderMaterial.prototype.setVector2 = function (name, value) {
  34137. this._checkUniform(name);
  34138. this._vectors2[name] = value;
  34139. return this;
  34140. };
  34141. ShaderMaterial.prototype.setVector3 = function (name, value) {
  34142. this._checkUniform(name);
  34143. this._vectors3[name] = value;
  34144. return this;
  34145. };
  34146. ShaderMaterial.prototype.setVector4 = function (name, value) {
  34147. this._checkUniform(name);
  34148. this._vectors4[name] = value;
  34149. return this;
  34150. };
  34151. ShaderMaterial.prototype.setMatrix = function (name, value) {
  34152. this._checkUniform(name);
  34153. this._matrices[name] = value;
  34154. return this;
  34155. };
  34156. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  34157. this._checkUniform(name);
  34158. this._matrices3x3[name] = value;
  34159. return this;
  34160. };
  34161. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  34162. this._checkUniform(name);
  34163. this._matrices2x2[name] = value;
  34164. return this;
  34165. };
  34166. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  34167. var scene = this.getScene();
  34168. var engine = scene.getEngine();
  34169. if (!this.checkReadyOnEveryCall) {
  34170. if (this._renderId === scene.getRenderId()) {
  34171. return true;
  34172. }
  34173. }
  34174. // Instances
  34175. var defines = [];
  34176. var fallbacks = new BABYLON.EffectFallbacks();
  34177. if (useInstances) {
  34178. defines.push("#define INSTANCES");
  34179. }
  34180. for (var index = 0; index < this._options.defines.length; index++) {
  34181. defines.push(this._options.defines[index]);
  34182. }
  34183. // Bones
  34184. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34185. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34186. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34187. fallbacks.addCPUSkinningFallback(0, mesh);
  34188. }
  34189. // Alpha test
  34190. if (engine.getAlphaTesting()) {
  34191. defines.push("#define ALPHATEST");
  34192. }
  34193. var previousEffect = this._effect;
  34194. var join = defines.join("\n");
  34195. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  34196. if (!this._effect.isReady()) {
  34197. return false;
  34198. }
  34199. if (previousEffect !== this._effect) {
  34200. scene.resetCachedMaterial();
  34201. }
  34202. this._renderId = scene.getRenderId();
  34203. return true;
  34204. };
  34205. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34206. var scene = this.getScene();
  34207. if (this._options.uniforms.indexOf("world") !== -1) {
  34208. this._effect.setMatrix("world", world);
  34209. }
  34210. if (this._options.uniforms.indexOf("worldView") !== -1) {
  34211. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  34212. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  34213. }
  34214. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  34215. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  34216. }
  34217. };
  34218. ShaderMaterial.prototype.bind = function (world, mesh) {
  34219. // Std values
  34220. this.bindOnlyWorldMatrix(world);
  34221. if (this.getScene().getCachedMaterial() !== this) {
  34222. if (this._options.uniforms.indexOf("view") !== -1) {
  34223. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  34224. }
  34225. if (this._options.uniforms.indexOf("projection") !== -1) {
  34226. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  34227. }
  34228. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  34229. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34230. }
  34231. // Bones
  34232. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34233. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34234. }
  34235. // Texture
  34236. for (var name in this._textures) {
  34237. this._effect.setTexture(name, this._textures[name]);
  34238. }
  34239. // Float
  34240. for (name in this._floats) {
  34241. this._effect.setFloat(name, this._floats[name]);
  34242. }
  34243. // Float s
  34244. for (name in this._floatsArrays) {
  34245. this._effect.setArray(name, this._floatsArrays[name]);
  34246. }
  34247. // Color3
  34248. for (name in this._colors3) {
  34249. this._effect.setColor3(name, this._colors3[name]);
  34250. }
  34251. // Color4
  34252. for (name in this._colors4) {
  34253. var color = this._colors4[name];
  34254. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  34255. }
  34256. // Vector2
  34257. for (name in this._vectors2) {
  34258. this._effect.setVector2(name, this._vectors2[name]);
  34259. }
  34260. // Vector3
  34261. for (name in this._vectors3) {
  34262. this._effect.setVector3(name, this._vectors3[name]);
  34263. }
  34264. // Vector4
  34265. for (name in this._vectors4) {
  34266. this._effect.setVector4(name, this._vectors4[name]);
  34267. }
  34268. // Matrix
  34269. for (name in this._matrices) {
  34270. this._effect.setMatrix(name, this._matrices[name]);
  34271. }
  34272. // Matrix 3x3
  34273. for (name in this._matrices3x3) {
  34274. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  34275. }
  34276. // Matrix 2x2
  34277. for (name in this._matrices2x2) {
  34278. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  34279. }
  34280. }
  34281. _super.prototype.bind.call(this, world, mesh);
  34282. };
  34283. ShaderMaterial.prototype.clone = function (name) {
  34284. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  34285. return newShaderMaterial;
  34286. };
  34287. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34288. if (forceDisposeTextures) {
  34289. for (var name in this._textures) {
  34290. this._textures[name].dispose();
  34291. }
  34292. }
  34293. this._textures = {};
  34294. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34295. };
  34296. ShaderMaterial.prototype.serialize = function () {
  34297. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34298. serializationObject.customType = "BABYLON.ShaderMaterial";
  34299. serializationObject.options = this._options;
  34300. serializationObject.shaderPath = this._shaderPath;
  34301. // Texture
  34302. serializationObject.textures = {};
  34303. for (var name in this._textures) {
  34304. serializationObject.textures[name] = this._textures[name].serialize();
  34305. }
  34306. // Float
  34307. serializationObject.floats = {};
  34308. for (name in this._floats) {
  34309. serializationObject.floats[name] = this._floats[name];
  34310. }
  34311. // Float s
  34312. serializationObject.floatArrays = {};
  34313. for (name in this._floatsArrays) {
  34314. serializationObject.floatArrays[name] = this._floatsArrays[name];
  34315. }
  34316. // Color3
  34317. serializationObject.colors3 = {};
  34318. for (name in this._colors3) {
  34319. serializationObject.colors3[name] = this._colors3[name].asArray();
  34320. }
  34321. // Color4
  34322. serializationObject.colors4 = {};
  34323. for (name in this._colors4) {
  34324. serializationObject.colors4[name] = this._colors4[name].asArray();
  34325. }
  34326. // Vector2
  34327. serializationObject.vectors2 = {};
  34328. for (name in this._vectors2) {
  34329. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  34330. }
  34331. // Vector3
  34332. serializationObject.vectors3 = {};
  34333. for (name in this._vectors3) {
  34334. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  34335. }
  34336. // Vector4
  34337. serializationObject.vectors4 = {};
  34338. for (name in this._vectors4) {
  34339. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  34340. }
  34341. // Matrix
  34342. serializationObject.matrices = {};
  34343. for (name in this._matrices) {
  34344. serializationObject.matrices[name] = this._matrices[name].asArray();
  34345. }
  34346. // Matrix 3x3
  34347. serializationObject.matrices3x3 = {};
  34348. for (name in this._matrices3x3) {
  34349. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  34350. }
  34351. // Matrix 2x2
  34352. serializationObject.matrices2x2 = {};
  34353. for (name in this._matrices2x2) {
  34354. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  34355. }
  34356. return serializationObject;
  34357. };
  34358. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  34359. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  34360. // Texture
  34361. for (var name in source.textures) {
  34362. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  34363. }
  34364. // Float
  34365. for (name in source.floats) {
  34366. material.setFloat(name, source.floats[name]);
  34367. }
  34368. // Float s
  34369. for (name in source.floatsArrays) {
  34370. material.setFloats(name, source.floatsArrays[name]);
  34371. }
  34372. // Color3
  34373. for (name in source.colors3) {
  34374. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  34375. }
  34376. // Color4
  34377. for (name in source.colors4) {
  34378. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  34379. }
  34380. // Vector2
  34381. for (name in source.vectors2) {
  34382. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  34383. }
  34384. // Vector3
  34385. for (name in source.vectors3) {
  34386. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  34387. }
  34388. // Vector4
  34389. for (name in source.vectors4) {
  34390. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  34391. }
  34392. // Matrix
  34393. for (name in source.matrices) {
  34394. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  34395. }
  34396. // Matrix 3x3
  34397. for (name in source.matrices3x3) {
  34398. material.setMatrix3x3(name, source.matrices3x3[name]);
  34399. }
  34400. // Matrix 2x2
  34401. for (name in source.matrices2x2) {
  34402. material.setMatrix2x2(name, source.matrices2x2[name]);
  34403. }
  34404. return material;
  34405. };
  34406. return ShaderMaterial;
  34407. })(BABYLON.Material);
  34408. BABYLON.ShaderMaterial = ShaderMaterial;
  34409. })(BABYLON || (BABYLON = {}));
  34410. var BABYLON;
  34411. (function (BABYLON) {
  34412. var Internals;
  34413. (function (Internals) {
  34414. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34415. // All values and structures referenced from:
  34416. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34417. var DDS_MAGIC = 0x20534444;
  34418. 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;
  34419. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34420. 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;
  34421. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34422. function FourCCToInt32(value) {
  34423. return value.charCodeAt(0) +
  34424. (value.charCodeAt(1) << 8) +
  34425. (value.charCodeAt(2) << 16) +
  34426. (value.charCodeAt(3) << 24);
  34427. }
  34428. function Int32ToFourCC(value) {
  34429. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34430. }
  34431. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34432. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34433. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34434. var headerLengthInt = 31; // The header length in 32 bit ints
  34435. // Offsets into the header array
  34436. var off_magic = 0;
  34437. var off_size = 1;
  34438. var off_flags = 2;
  34439. var off_height = 3;
  34440. var off_width = 4;
  34441. var off_mipmapCount = 7;
  34442. var off_pfFlags = 20;
  34443. var off_pfFourCC = 21;
  34444. var off_RGBbpp = 22;
  34445. var off_RMask = 23;
  34446. var off_GMask = 24;
  34447. var off_BMask = 25;
  34448. var off_AMask = 26;
  34449. var off_caps1 = 27;
  34450. var off_caps2 = 28;
  34451. ;
  34452. var DDSTools = (function () {
  34453. function DDSTools() {
  34454. }
  34455. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34456. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34457. var mipmapCount = 1;
  34458. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34459. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34460. }
  34461. return {
  34462. width: header[off_width],
  34463. height: header[off_height],
  34464. mipmapCount: mipmapCount,
  34465. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34466. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34467. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34468. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  34469. };
  34470. };
  34471. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34472. var byteArray = new Uint8Array(dataLength);
  34473. var srcData = new Uint8Array(arrayBuffer);
  34474. var index = 0;
  34475. for (var y = height - 1; y >= 0; y--) {
  34476. for (var x = 0; x < width; x++) {
  34477. var srcPos = dataOffset + (x + y * width) * 4;
  34478. byteArray[index + 2] = srcData[srcPos];
  34479. byteArray[index + 1] = srcData[srcPos + 1];
  34480. byteArray[index] = srcData[srcPos + 2];
  34481. byteArray[index + 3] = srcData[srcPos + 3];
  34482. index += 4;
  34483. }
  34484. }
  34485. return byteArray;
  34486. };
  34487. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34488. var byteArray = new Uint8Array(dataLength);
  34489. var srcData = new Uint8Array(arrayBuffer);
  34490. var index = 0;
  34491. for (var y = height - 1; y >= 0; y--) {
  34492. for (var x = 0; x < width; x++) {
  34493. var srcPos = dataOffset + (x + y * width) * 3;
  34494. byteArray[index + 2] = srcData[srcPos];
  34495. byteArray[index + 1] = srcData[srcPos + 1];
  34496. byteArray[index] = srcData[srcPos + 2];
  34497. index += 3;
  34498. }
  34499. }
  34500. return byteArray;
  34501. };
  34502. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34503. var byteArray = new Uint8Array(dataLength);
  34504. var srcData = new Uint8Array(arrayBuffer);
  34505. var index = 0;
  34506. for (var y = height - 1; y >= 0; y--) {
  34507. for (var x = 0; x < width; x++) {
  34508. var srcPos = dataOffset + (x + y * width);
  34509. byteArray[index] = srcData[srcPos];
  34510. index++;
  34511. }
  34512. }
  34513. return byteArray;
  34514. };
  34515. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  34516. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  34517. if (header[off_magic] != DDS_MAGIC) {
  34518. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34519. return;
  34520. }
  34521. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34522. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34523. return;
  34524. }
  34525. if (info.isFourCC) {
  34526. fourCC = header[off_pfFourCC];
  34527. switch (fourCC) {
  34528. case FOURCC_DXT1:
  34529. blockBytes = 8;
  34530. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34531. break;
  34532. case FOURCC_DXT3:
  34533. blockBytes = 16;
  34534. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34535. break;
  34536. case FOURCC_DXT5:
  34537. blockBytes = 16;
  34538. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34539. break;
  34540. default:
  34541. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34542. return;
  34543. }
  34544. }
  34545. mipmapCount = 1;
  34546. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34547. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34548. }
  34549. var bpp = header[off_RGBbpp];
  34550. for (var face = 0; face < faces; face++) {
  34551. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34552. width = header[off_width];
  34553. height = header[off_height];
  34554. dataOffset = header[off_size] + 4;
  34555. for (i = 0; i < mipmapCount; ++i) {
  34556. if (info.isRGB) {
  34557. if (bpp === 24) {
  34558. dataLength = width * height * 3;
  34559. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34560. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34561. }
  34562. else {
  34563. dataLength = width * height * 4;
  34564. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34565. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34566. }
  34567. }
  34568. else if (info.isLuminance) {
  34569. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34570. var unpaddedRowSize = width;
  34571. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34572. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34573. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34574. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34575. }
  34576. else {
  34577. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34578. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34579. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  34580. }
  34581. dataOffset += dataLength;
  34582. width *= 0.5;
  34583. height *= 0.5;
  34584. width = Math.max(1.0, width);
  34585. height = Math.max(1.0, height);
  34586. }
  34587. }
  34588. };
  34589. return DDSTools;
  34590. })();
  34591. Internals.DDSTools = DDSTools;
  34592. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34593. })(BABYLON || (BABYLON = {}));
  34594. var BABYLON;
  34595. (function (BABYLON) {
  34596. var CannonJSPlugin = (function () {
  34597. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  34598. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  34599. if (iterations === void 0) { iterations = 10; }
  34600. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  34601. this.name = "CannonJSPlugin";
  34602. this._physicsMaterials = [];
  34603. this._fixedTimeStep = 1 / 60;
  34604. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34605. this._currentCollisionGroup = 2;
  34606. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  34607. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  34608. this._tmpPosition = BABYLON.Vector3.Zero();
  34609. this._tmpQuaternion = new BABYLON.Quaternion();
  34610. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  34611. this._tmpDeltaRotation = new BABYLON.Quaternion();
  34612. this._tmpUnityRotation = new BABYLON.Quaternion();
  34613. if (!this.isSupported()) {
  34614. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  34615. return;
  34616. }
  34617. this.world = new CANNON.World();
  34618. this.world.broadphase = new CANNON.NaiveBroadphase();
  34619. this.world.solver.iterations = iterations;
  34620. }
  34621. CannonJSPlugin.prototype.setGravity = function (gravity) {
  34622. this.world.gravity.copy(gravity);
  34623. };
  34624. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  34625. this._fixedTimeStep = timeStep;
  34626. };
  34627. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  34628. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  34629. };
  34630. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34631. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34632. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34633. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34634. };
  34635. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34636. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34637. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34638. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34639. };
  34640. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34641. //parent-child relationship. Does this impostor has a parent impostor?
  34642. if (impostor.parent) {
  34643. if (impostor.physicsBody) {
  34644. this.removePhysicsBody(impostor);
  34645. //TODO is that needed?
  34646. impostor.forceUpdate();
  34647. }
  34648. return;
  34649. }
  34650. //should a new body be created for this impostor?
  34651. if (impostor.isBodyInitRequired()) {
  34652. var shape = this._createShape(impostor);
  34653. //unregister events, if body is being changed
  34654. var oldBody = impostor.physicsBody;
  34655. if (oldBody) {
  34656. this.removePhysicsBody(impostor);
  34657. }
  34658. //create the body and material
  34659. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  34660. var bodyCreationObject = {
  34661. mass: impostor.getParam("mass"),
  34662. material: material
  34663. };
  34664. // A simple extend, in case native options were used.
  34665. var nativeOptions = impostor.getParam("nativeOptions");
  34666. for (var key in nativeOptions) {
  34667. if (nativeOptions.hasOwnProperty(key)) {
  34668. bodyCreationObject[key] = nativeOptions[key];
  34669. }
  34670. }
  34671. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  34672. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  34673. this.world.addEventListener("preStep", impostor.beforeStep);
  34674. this.world.addEventListener("postStep", impostor.afterStep);
  34675. impostor.physicsBody.addShape(shape);
  34676. this.world.add(impostor.physicsBody);
  34677. //try to keep the body moving in the right direction by taking old properties.
  34678. //Should be tested!
  34679. if (oldBody) {
  34680. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  34681. impostor.physicsBody[param].copy(oldBody[param]);
  34682. });
  34683. }
  34684. this._processChildMeshes(impostor);
  34685. }
  34686. //now update the body's transformation
  34687. this._updatePhysicsBodyTransformation(impostor);
  34688. };
  34689. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  34690. var _this = this;
  34691. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  34692. if (meshChildren.length) {
  34693. var processMesh = function (localPosition, mesh) {
  34694. var childImpostor = mesh.getPhysicsImpostor();
  34695. if (childImpostor) {
  34696. var parent = childImpostor.parent;
  34697. if (parent !== mainImpostor) {
  34698. var localPosition = mesh.position;
  34699. if (childImpostor.physicsBody) {
  34700. _this.removePhysicsBody(childImpostor);
  34701. childImpostor.physicsBody = null;
  34702. }
  34703. childImpostor.parent = mainImpostor;
  34704. childImpostor.resetUpdateFlags();
  34705. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  34706. //Add the mass of the children.
  34707. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  34708. }
  34709. }
  34710. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  34711. };
  34712. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  34713. }
  34714. };
  34715. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34716. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  34717. this.world.removeEventListener("preStep", impostor.beforeStep);
  34718. this.world.removeEventListener("postStep", impostor.afterStep);
  34719. this.world.remove(impostor.physicsBody);
  34720. };
  34721. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  34722. var mainBody = impostorJoint.mainImpostor.physicsBody;
  34723. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  34724. if (!mainBody || !connectedBody) {
  34725. return;
  34726. }
  34727. var constraint;
  34728. var jointData = impostorJoint.joint.jointData;
  34729. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34730. var constraintData = {
  34731. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  34732. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  34733. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  34734. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  34735. maxForce: jointData.nativeParams.maxForce,
  34736. collideConnected: !!jointData.collision
  34737. };
  34738. //Not needed, Cannon has a collideConnected flag
  34739. /*if (!jointData.collision) {
  34740. //add 1st body to a collision group of its own, if it is not in 1
  34741. if (mainBody.collisionFilterGroup === 1) {
  34742. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  34743. this._currentCollisionGroup <<= 1;
  34744. }
  34745. if (connectedBody.collisionFilterGroup === 1) {
  34746. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  34747. this._currentCollisionGroup <<= 1;
  34748. }
  34749. //add their mask to the collisionFilterMask of each other:
  34750. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  34751. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  34752. }*/
  34753. switch (impostorJoint.joint.type) {
  34754. case BABYLON.PhysicsJoint.HingeJoint:
  34755. case BABYLON.PhysicsJoint.Hinge2Joint:
  34756. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  34757. break;
  34758. case BABYLON.PhysicsJoint.DistanceJoint:
  34759. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  34760. break;
  34761. case BABYLON.PhysicsJoint.SpringJoint:
  34762. var springData = jointData;
  34763. constraint = new CANNON.Spring(mainBody, connectedBody, {
  34764. restLength: springData.length,
  34765. stiffness: springData.stiffness,
  34766. damping: springData.damping,
  34767. localAnchorA: constraintData.pivotA,
  34768. localAnchorB: constraintData.pivotB
  34769. });
  34770. break;
  34771. case BABYLON.PhysicsJoint.PointToPointJoint:
  34772. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  34773. default:
  34774. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  34775. break;
  34776. }
  34777. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  34778. constraint.collideConnected = !!jointData.collision;
  34779. impostorJoint.joint.physicsJoint = constraint;
  34780. //don't add spring as constraint, as it is not one.
  34781. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  34782. this.world.addConstraint(constraint);
  34783. }
  34784. else {
  34785. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  34786. constraint.applyForce();
  34787. });
  34788. }
  34789. };
  34790. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  34791. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  34792. };
  34793. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  34794. var index;
  34795. var mat;
  34796. for (index = 0; index < this._physicsMaterials.length; index++) {
  34797. mat = this._physicsMaterials[index];
  34798. if (mat.friction === friction && mat.restitution === restitution) {
  34799. return mat;
  34800. }
  34801. }
  34802. var currentMat = new CANNON.Material(name);
  34803. currentMat.friction = friction;
  34804. currentMat.restitution = restitution;
  34805. this._physicsMaterials.push(currentMat);
  34806. return currentMat;
  34807. };
  34808. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  34809. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  34810. };
  34811. CannonJSPlugin.prototype._createShape = function (impostor) {
  34812. var object = impostor.object;
  34813. var returnValue;
  34814. var extendSize = impostor.getObjectExtendSize();
  34815. switch (impostor.type) {
  34816. case BABYLON.PhysicsEngine.SphereImpostor:
  34817. var radiusX = extendSize.x;
  34818. var radiusY = extendSize.y;
  34819. var radiusZ = extendSize.z;
  34820. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  34821. break;
  34822. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  34823. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34824. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  34825. break;
  34826. case BABYLON.PhysicsImpostor.BoxImpostor:
  34827. var box = extendSize.scale(0.5);
  34828. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  34829. break;
  34830. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34831. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  34832. returnValue = new CANNON.Plane();
  34833. break;
  34834. case BABYLON.PhysicsImpostor.MeshImpostor:
  34835. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  34836. var rawFaces = object.getIndices ? object.getIndices() : [];
  34837. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  34838. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  34839. break;
  34840. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  34841. returnValue = this._createHeightmap(object);
  34842. break;
  34843. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34844. returnValue = new CANNON.Particle();
  34845. break;
  34846. }
  34847. return returnValue;
  34848. };
  34849. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  34850. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34851. var matrix = [];
  34852. //For now pointDepth will not be used and will be automatically calculated.
  34853. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  34854. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  34855. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  34856. var elementSize = dim * 2 / arraySize;
  34857. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  34858. for (var i = 0; i < pos.length; i = i + 3) {
  34859. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  34860. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  34861. var y = pos[i + 1] + minY;
  34862. if (!matrix[x]) {
  34863. matrix[x] = [];
  34864. }
  34865. if (!matrix[x][z]) {
  34866. matrix[x][z] = y;
  34867. }
  34868. matrix[x][z] = Math.max(y, matrix[x][z]);
  34869. }
  34870. for (var x = 0; x <= arraySize; ++x) {
  34871. if (!matrix[x]) {
  34872. var loc = 1;
  34873. while (!matrix[(x + loc) % arraySize]) {
  34874. loc++;
  34875. }
  34876. matrix[x] = matrix[(x + loc) % arraySize].slice();
  34877. }
  34878. for (var z = 0; z <= arraySize; ++z) {
  34879. if (!matrix[x][z]) {
  34880. var loc = 1;
  34881. var newValue;
  34882. while (newValue === undefined) {
  34883. newValue = matrix[x][(z + loc++) % arraySize];
  34884. }
  34885. matrix[x][z] = newValue;
  34886. }
  34887. }
  34888. }
  34889. var shape = new CANNON.Heightfield(matrix, {
  34890. elementSize: elementSize
  34891. });
  34892. //For future reference, needed for body transformation
  34893. shape.minY = minY;
  34894. return shape;
  34895. };
  34896. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  34897. var object = impostor.object;
  34898. //make sure it is updated...
  34899. object.computeWorldMatrix && object.computeWorldMatrix(true);
  34900. // The delta between the mesh position and the mesh bounding box center
  34901. var center = impostor.getObjectCenter();
  34902. var extendSize = impostor.getObjectExtendSize();
  34903. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  34904. this._tmpPosition.copyFrom(center);
  34905. var quaternion = object.rotationQuaternion;
  34906. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  34907. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  34908. //-90 DEG in X, precalculated
  34909. quaternion = quaternion.multiply(this._minus90X);
  34910. //Invert! (Precalculated, 90 deg in X)
  34911. //No need to clone. this will never change.
  34912. impostor.setDeltaRotation(this._plus90X);
  34913. }
  34914. //If it is a heightfield, if should be centered.
  34915. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  34916. var mesh = object;
  34917. //calculate the correct body position:
  34918. var rotationQuaternion = mesh.rotationQuaternion;
  34919. mesh.rotationQuaternion = this._tmpUnityRotation;
  34920. mesh.computeWorldMatrix(true);
  34921. //get original center with no rotation
  34922. var c = center.clone();
  34923. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  34924. //rotation is back
  34925. mesh.rotationQuaternion = rotationQuaternion;
  34926. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  34927. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  34928. mesh.setPivotMatrix(p);
  34929. mesh.computeWorldMatrix(true);
  34930. //calculate the translation
  34931. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  34932. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  34933. //add it inverted to the delta
  34934. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  34935. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  34936. mesh.setPivotMatrix(oldPivot);
  34937. mesh.computeWorldMatrix(true);
  34938. }
  34939. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  34940. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  34941. this._tmpPosition.copyFrom(object.position);
  34942. }
  34943. impostor.setDeltaPosition(this._tmpDeltaPosition);
  34944. //Now update the impostor object
  34945. impostor.physicsBody.position.copy(this._tmpPosition);
  34946. impostor.physicsBody.quaternion.copy(quaternion);
  34947. };
  34948. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  34949. impostor.object.position.copyFrom(impostor.physicsBody.position);
  34950. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  34951. };
  34952. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  34953. impostor.physicsBody.position.copy(newPosition);
  34954. impostor.physicsBody.quaternion.copy(newRotation);
  34955. };
  34956. CannonJSPlugin.prototype.isSupported = function () {
  34957. return window.CANNON !== undefined;
  34958. };
  34959. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  34960. impostor.physicsBody.velocity.copy(velocity);
  34961. };
  34962. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  34963. impostor.physicsBody.angularVelocity.copy(velocity);
  34964. };
  34965. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  34966. var v = impostor.physicsBody.velocity;
  34967. if (!v)
  34968. return null;
  34969. return new BABYLON.Vector3(v.x, v.y, v.z);
  34970. };
  34971. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  34972. var v = impostor.physicsBody.angularVelocity;
  34973. if (!v)
  34974. return null;
  34975. return new BABYLON.Vector3(v.x, v.y, v.z);
  34976. };
  34977. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  34978. impostor.physicsBody.mass = mass;
  34979. impostor.physicsBody.updateMassProperties();
  34980. };
  34981. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  34982. impostor.physicsBody.sleep();
  34983. };
  34984. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  34985. impostor.physicsBody.wakeUp();
  34986. };
  34987. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  34988. joint.physicsJoint.distance = maxDistance;
  34989. };
  34990. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  34991. if (!motorIndex) {
  34992. joint.physicsJoint.enableMotor();
  34993. }
  34994. };
  34995. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  34996. if (!motorIndex) {
  34997. joint.physicsJoint.disableMotor();
  34998. }
  34999. };
  35000. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35001. if (!motorIndex) {
  35002. joint.physicsJoint.enableMotor();
  35003. joint.physicsJoint.setMotorSpeed(speed);
  35004. if (maxForce) {
  35005. this.setLimit(joint, maxForce);
  35006. }
  35007. }
  35008. };
  35009. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  35010. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  35011. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  35012. };
  35013. CannonJSPlugin.prototype.dispose = function () {
  35014. //nothing to do, actually.
  35015. };
  35016. return CannonJSPlugin;
  35017. })();
  35018. BABYLON.CannonJSPlugin = CannonJSPlugin;
  35019. })(BABYLON || (BABYLON = {}));
  35020. var BABYLON;
  35021. (function (BABYLON) {
  35022. var OimoJSPlugin = (function () {
  35023. function OimoJSPlugin(iterations) {
  35024. this.name = "OimoJSPlugin";
  35025. this._tmpImpostorsArray = [];
  35026. this._tmpPositionVector = BABYLON.Vector3.Zero();
  35027. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  35028. this.world.clear();
  35029. //making sure no stats are calculated
  35030. this.world.isNoStat = true;
  35031. }
  35032. OimoJSPlugin.prototype.setGravity = function (gravity) {
  35033. this.world.gravity.copy(gravity);
  35034. };
  35035. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  35036. this.world.timeStep = timeStep;
  35037. };
  35038. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  35039. var _this = this;
  35040. impostors.forEach(function (impostor) {
  35041. impostor.beforeStep();
  35042. });
  35043. this.world.step();
  35044. impostors.forEach(function (impostor) {
  35045. impostor.afterStep();
  35046. //update the ordered impostors array
  35047. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  35048. });
  35049. //check for collisions
  35050. var contact = this.world.contacts;
  35051. while (contact !== null) {
  35052. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  35053. contact = contact.next;
  35054. continue;
  35055. }
  35056. //is this body colliding with any other? get the impostor
  35057. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  35058. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  35059. if (!mainImpostor || !collidingImpostor) {
  35060. contact = contact.next;
  35061. continue;
  35062. }
  35063. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  35064. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  35065. contact = contact.next;
  35066. }
  35067. };
  35068. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  35069. var mass = impostor.physicsBody.massInfo.mass;
  35070. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  35071. };
  35072. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  35073. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  35074. this.applyImpulse(impostor, force, contactPoint);
  35075. };
  35076. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  35077. var _this = this;
  35078. //parent-child relationship. Does this impostor has a parent impostor?
  35079. if (impostor.parent) {
  35080. if (impostor.physicsBody) {
  35081. this.removePhysicsBody(impostor);
  35082. //TODO is that needed?
  35083. impostor.forceUpdate();
  35084. }
  35085. return;
  35086. }
  35087. if (impostor.isBodyInitRequired()) {
  35088. var bodyConfig = {
  35089. name: impostor.uniqueId,
  35090. //Oimo must have mass, also for static objects.
  35091. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  35092. size: [],
  35093. type: [],
  35094. pos: [],
  35095. rot: [],
  35096. move: impostor.getParam("mass") !== 0,
  35097. //Supporting older versions of Oimo
  35098. world: this.world
  35099. };
  35100. var impostors = [impostor];
  35101. function addToArray(parent) {
  35102. if (!parent.getChildMeshes)
  35103. return;
  35104. parent.getChildMeshes().forEach(function (m) {
  35105. if (m.physicsImpostor) {
  35106. impostors.push(m.physicsImpostor);
  35107. m.physicsImpostor._init();
  35108. }
  35109. });
  35110. }
  35111. addToArray(impostor.object);
  35112. function checkWithEpsilon(value) {
  35113. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  35114. }
  35115. impostors.forEach(function (i) {
  35116. //get the correct bounding box
  35117. var oldQuaternion = i.object.rotationQuaternion;
  35118. var rot = new OIMO.Euler().setFromQuaternion({
  35119. x: impostor.object.rotationQuaternion.x,
  35120. y: impostor.object.rotationQuaternion.y,
  35121. z: impostor.object.rotationQuaternion.z,
  35122. s: impostor.object.rotationQuaternion.w
  35123. });
  35124. var extendSize = i.getObjectExtendSize();
  35125. if (i === impostor) {
  35126. var center = impostor.getObjectCenter();
  35127. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  35128. //Can also use Array.prototype.push.apply
  35129. bodyConfig.pos.push(center.x);
  35130. bodyConfig.pos.push(center.y);
  35131. bodyConfig.pos.push(center.z);
  35132. //tmp solution
  35133. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  35134. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  35135. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  35136. }
  35137. else {
  35138. bodyConfig.pos.push(i.object.position.x);
  35139. bodyConfig.pos.push(i.object.position.y);
  35140. bodyConfig.pos.push(i.object.position.z);
  35141. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  35142. bodyConfig.rot.push(0);
  35143. bodyConfig.rot.push(0);
  35144. bodyConfig.rot.push(0);
  35145. }
  35146. // register mesh
  35147. switch (i.type) {
  35148. case BABYLON.PhysicsImpostor.ParticleImpostor:
  35149. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  35150. case BABYLON.PhysicsImpostor.SphereImpostor:
  35151. var radiusX = extendSize.x;
  35152. var radiusY = extendSize.y;
  35153. var radiusZ = extendSize.z;
  35154. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  35155. bodyConfig.type.push('sphere');
  35156. //due to the way oimo works with compounds, add 3 times
  35157. bodyConfig.size.push(size);
  35158. bodyConfig.size.push(size);
  35159. bodyConfig.size.push(size);
  35160. break;
  35161. case BABYLON.PhysicsImpostor.CylinderImpostor:
  35162. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  35163. var sizeY = checkWithEpsilon(extendSize.y);
  35164. bodyConfig.type.push('cylinder');
  35165. bodyConfig.size.push(sizeX);
  35166. bodyConfig.size.push(sizeY);
  35167. //due to the way oimo works with compounds, add one more value.
  35168. bodyConfig.size.push(sizeY);
  35169. break;
  35170. case BABYLON.PhysicsImpostor.PlaneImpostor:
  35171. case BABYLON.PhysicsImpostor.BoxImpostor:
  35172. default:
  35173. var sizeX = checkWithEpsilon(extendSize.x);
  35174. var sizeY = checkWithEpsilon(extendSize.y);
  35175. var sizeZ = checkWithEpsilon(extendSize.z);
  35176. bodyConfig.type.push('box');
  35177. bodyConfig.size.push(sizeX);
  35178. bodyConfig.size.push(sizeY);
  35179. bodyConfig.size.push(sizeZ);
  35180. break;
  35181. }
  35182. //actually not needed, but hey...
  35183. i.object.rotationQuaternion = oldQuaternion;
  35184. });
  35185. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  35186. }
  35187. else {
  35188. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  35189. }
  35190. impostor.setDeltaPosition(this._tmpPositionVector);
  35191. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  35192. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  35193. };
  35194. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35195. //impostor.physicsBody.dispose();
  35196. //Same as : (older oimo versions)
  35197. this.world.removeRigidBody(impostor.physicsBody);
  35198. };
  35199. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35200. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35201. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35202. if (!mainBody || !connectedBody) {
  35203. return;
  35204. }
  35205. var jointData = impostorJoint.joint.jointData;
  35206. var options = jointData.nativeParams || {};
  35207. var type;
  35208. var nativeJointData = {
  35209. body1: mainBody,
  35210. body2: connectedBody,
  35211. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  35212. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  35213. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  35214. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  35215. min: options.min,
  35216. max: options.max,
  35217. collision: options.collision || jointData.collision,
  35218. spring: options.spring,
  35219. //supporting older version of Oimo
  35220. world: this.world
  35221. };
  35222. switch (impostorJoint.joint.type) {
  35223. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35224. type = "jointBall";
  35225. break;
  35226. case BABYLON.PhysicsJoint.SpringJoint:
  35227. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  35228. var springData = jointData;
  35229. nativeJointData.min = springData.length || nativeJointData.min;
  35230. //Max should also be set, just make sure it is at least min
  35231. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  35232. case BABYLON.PhysicsJoint.DistanceJoint:
  35233. type = "jointDistance";
  35234. nativeJointData.max = jointData.maxDistance;
  35235. break;
  35236. case BABYLON.PhysicsJoint.PrismaticJoint:
  35237. type = "jointPrisme";
  35238. break;
  35239. case BABYLON.PhysicsJoint.SliderJoint:
  35240. type = "jointSlide";
  35241. break;
  35242. case BABYLON.PhysicsJoint.WheelJoint:
  35243. type = "jointWheel";
  35244. break;
  35245. case BABYLON.PhysicsJoint.HingeJoint:
  35246. default:
  35247. type = "jointHinge";
  35248. break;
  35249. }
  35250. nativeJointData.type = type;
  35251. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  35252. };
  35253. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  35254. //Bug in Oimo prevents us from disposing a joint in the playground
  35255. //joint.joint.physicsJoint.dispose();
  35256. //So we will bruteforce it!
  35257. try {
  35258. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  35259. }
  35260. catch (e) {
  35261. BABYLON.Tools.Warn(e);
  35262. }
  35263. };
  35264. OimoJSPlugin.prototype.isSupported = function () {
  35265. return OIMO !== undefined;
  35266. };
  35267. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35268. if (!impostor.physicsBody.sleeping) {
  35269. //TODO check that
  35270. if (impostor.physicsBody.shapes.next) {
  35271. var parentShape = this._getLastShape(impostor.physicsBody);
  35272. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  35273. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  35274. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  35275. }
  35276. else {
  35277. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  35278. }
  35279. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  35280. }
  35281. };
  35282. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35283. var body = impostor.physicsBody;
  35284. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  35285. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  35286. body.syncShapes();
  35287. body.awake();
  35288. };
  35289. OimoJSPlugin.prototype._getLastShape = function (body) {
  35290. var lastShape = body.shapes;
  35291. while (lastShape.next) {
  35292. lastShape = lastShape.next;
  35293. }
  35294. return lastShape;
  35295. };
  35296. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35297. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  35298. };
  35299. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35300. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  35301. };
  35302. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35303. var v = impostor.physicsBody.linearVelocity;
  35304. if (!v)
  35305. return null;
  35306. return new BABYLON.Vector3(v.x, v.y, v.z);
  35307. };
  35308. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35309. var v = impostor.physicsBody.angularVelocity;
  35310. if (!v)
  35311. return null;
  35312. return new BABYLON.Vector3(v.x, v.y, v.z);
  35313. };
  35314. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35315. var staticBody = mass === 0;
  35316. //this will actually set the body's density and not its mass.
  35317. //But this is how oimo treats the mass variable.
  35318. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  35319. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  35320. };
  35321. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  35322. impostor.physicsBody.sleep();
  35323. };
  35324. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  35325. impostor.physicsBody.awake();
  35326. };
  35327. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35328. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  35329. if (minDistance !== void 0) {
  35330. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  35331. }
  35332. };
  35333. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35334. //TODO separate rotational and transational motors.
  35335. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  35336. if (motor) {
  35337. motor.setMotor(speed, maxForce);
  35338. }
  35339. };
  35340. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  35341. //TODO separate rotational and transational motors.
  35342. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  35343. if (motor) {
  35344. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  35345. }
  35346. };
  35347. OimoJSPlugin.prototype.dispose = function () {
  35348. this.world.clear();
  35349. };
  35350. return OimoJSPlugin;
  35351. })();
  35352. BABYLON.OimoJSPlugin = OimoJSPlugin;
  35353. })(BABYLON || (BABYLON = {}));
  35354. var BABYLON;
  35355. (function (BABYLON) {
  35356. var DisplayPassPostProcess = (function (_super) {
  35357. __extends(DisplayPassPostProcess, _super);
  35358. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35359. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  35360. }
  35361. return DisplayPassPostProcess;
  35362. })(BABYLON.PostProcess);
  35363. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  35364. })(BABYLON || (BABYLON = {}));
  35365. var BABYLON;
  35366. (function (BABYLON) {
  35367. var SimplificationSettings = (function () {
  35368. function SimplificationSettings(quality, distance, optimizeMesh) {
  35369. this.quality = quality;
  35370. this.distance = distance;
  35371. this.optimizeMesh = optimizeMesh;
  35372. }
  35373. return SimplificationSettings;
  35374. })();
  35375. BABYLON.SimplificationSettings = SimplificationSettings;
  35376. var SimplificationQueue = (function () {
  35377. function SimplificationQueue() {
  35378. this.running = false;
  35379. this._simplificationArray = [];
  35380. }
  35381. SimplificationQueue.prototype.addTask = function (task) {
  35382. this._simplificationArray.push(task);
  35383. };
  35384. SimplificationQueue.prototype.executeNext = function () {
  35385. var task = this._simplificationArray.pop();
  35386. if (task) {
  35387. this.running = true;
  35388. this.runSimplification(task);
  35389. }
  35390. else {
  35391. this.running = false;
  35392. }
  35393. };
  35394. SimplificationQueue.prototype.runSimplification = function (task) {
  35395. var _this = this;
  35396. if (task.parallelProcessing) {
  35397. //parallel simplifier
  35398. task.settings.forEach(function (setting) {
  35399. var simplifier = _this.getSimplifier(task);
  35400. simplifier.simplify(setting, function (newMesh) {
  35401. task.mesh.addLODLevel(setting.distance, newMesh);
  35402. newMesh.isVisible = true;
  35403. //check if it is the last
  35404. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  35405. //all done, run the success callback.
  35406. task.successCallback();
  35407. }
  35408. _this.executeNext();
  35409. });
  35410. });
  35411. }
  35412. else {
  35413. //single simplifier.
  35414. var simplifier = this.getSimplifier(task);
  35415. var runDecimation = function (setting, callback) {
  35416. simplifier.simplify(setting, function (newMesh) {
  35417. task.mesh.addLODLevel(setting.distance, newMesh);
  35418. newMesh.isVisible = true;
  35419. //run the next quality level
  35420. callback();
  35421. });
  35422. };
  35423. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  35424. runDecimation(task.settings[loop.index], function () {
  35425. loop.executeNext();
  35426. });
  35427. }, function () {
  35428. //execution ended, run the success callback.
  35429. if (task.successCallback) {
  35430. task.successCallback();
  35431. }
  35432. _this.executeNext();
  35433. });
  35434. }
  35435. };
  35436. SimplificationQueue.prototype.getSimplifier = function (task) {
  35437. switch (task.simplificationType) {
  35438. case SimplificationType.QUADRATIC:
  35439. default:
  35440. return new QuadraticErrorSimplification(task.mesh);
  35441. }
  35442. };
  35443. return SimplificationQueue;
  35444. })();
  35445. BABYLON.SimplificationQueue = SimplificationQueue;
  35446. /**
  35447. * The implemented types of simplification.
  35448. * At the moment only Quadratic Error Decimation is implemented.
  35449. */
  35450. (function (SimplificationType) {
  35451. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  35452. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  35453. var SimplificationType = BABYLON.SimplificationType;
  35454. var DecimationTriangle = (function () {
  35455. function DecimationTriangle(vertices) {
  35456. this.vertices = vertices;
  35457. this.error = new Array(4);
  35458. this.deleted = false;
  35459. this.isDirty = false;
  35460. this.deletePending = false;
  35461. this.borderFactor = 0;
  35462. }
  35463. return DecimationTriangle;
  35464. })();
  35465. BABYLON.DecimationTriangle = DecimationTriangle;
  35466. var DecimationVertex = (function () {
  35467. function DecimationVertex(position, id) {
  35468. this.position = position;
  35469. this.id = id;
  35470. this.isBorder = true;
  35471. this.q = new QuadraticMatrix();
  35472. this.triangleCount = 0;
  35473. this.triangleStart = 0;
  35474. this.originalOffsets = [];
  35475. }
  35476. DecimationVertex.prototype.updatePosition = function (newPosition) {
  35477. this.position.copyFrom(newPosition);
  35478. };
  35479. return DecimationVertex;
  35480. })();
  35481. BABYLON.DecimationVertex = DecimationVertex;
  35482. var QuadraticMatrix = (function () {
  35483. function QuadraticMatrix(data) {
  35484. this.data = new Array(10);
  35485. for (var i = 0; i < 10; ++i) {
  35486. if (data && data[i]) {
  35487. this.data[i] = data[i];
  35488. }
  35489. else {
  35490. this.data[i] = 0;
  35491. }
  35492. }
  35493. }
  35494. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  35495. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  35496. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  35497. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  35498. return det;
  35499. };
  35500. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  35501. for (var i = 0; i < 10; ++i) {
  35502. this.data[i] += matrix.data[i];
  35503. }
  35504. };
  35505. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  35506. for (var i = 0; i < 10; ++i) {
  35507. this.data[i] += data[i];
  35508. }
  35509. };
  35510. QuadraticMatrix.prototype.add = function (matrix) {
  35511. var m = new QuadraticMatrix();
  35512. for (var i = 0; i < 10; ++i) {
  35513. m.data[i] = this.data[i] + matrix.data[i];
  35514. }
  35515. return m;
  35516. };
  35517. QuadraticMatrix.FromData = function (a, b, c, d) {
  35518. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  35519. };
  35520. //returning an array to avoid garbage collection
  35521. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  35522. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  35523. };
  35524. return QuadraticMatrix;
  35525. })();
  35526. BABYLON.QuadraticMatrix = QuadraticMatrix;
  35527. var Reference = (function () {
  35528. function Reference(vertexId, triangleId) {
  35529. this.vertexId = vertexId;
  35530. this.triangleId = triangleId;
  35531. }
  35532. return Reference;
  35533. })();
  35534. BABYLON.Reference = Reference;
  35535. /**
  35536. * An implementation of the Quadratic Error simplification algorithm.
  35537. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  35538. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  35539. * @author RaananW
  35540. */
  35541. var QuadraticErrorSimplification = (function () {
  35542. function QuadraticErrorSimplification(_mesh) {
  35543. this._mesh = _mesh;
  35544. this.initialized = false;
  35545. this.syncIterations = 5000;
  35546. this.aggressiveness = 7;
  35547. this.decimationIterations = 100;
  35548. this.boundingBoxEpsilon = BABYLON.Epsilon;
  35549. }
  35550. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  35551. var _this = this;
  35552. this.initDecimatedMesh();
  35553. //iterating through the submeshes array, one after the other.
  35554. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  35555. _this.initWithMesh(loop.index, function () {
  35556. _this.runDecimation(settings, loop.index, function () {
  35557. loop.executeNext();
  35558. });
  35559. }, settings.optimizeMesh);
  35560. }, function () {
  35561. setTimeout(function () {
  35562. successCallback(_this._reconstructedMesh);
  35563. }, 0);
  35564. });
  35565. };
  35566. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  35567. var _this = this;
  35568. var gCount = 0;
  35569. triangle.vertices.forEach(function (vertex) {
  35570. var count = 0;
  35571. var vPos = vertex.position;
  35572. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  35573. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  35574. ++count;
  35575. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  35576. ++count;
  35577. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  35578. ++count;
  35579. if (count > 1) {
  35580. ++gCount;
  35581. }
  35582. ;
  35583. });
  35584. if (gCount > 1) {
  35585. console.log(triangle, gCount);
  35586. }
  35587. return gCount > 1;
  35588. };
  35589. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  35590. var _this = this;
  35591. var targetCount = ~~(this.triangles.length * settings.quality);
  35592. var deletedTriangles = 0;
  35593. var triangleCount = this.triangles.length;
  35594. var iterationFunction = function (iteration, callback) {
  35595. setTimeout(function () {
  35596. if (iteration % 5 === 0) {
  35597. _this.updateMesh(iteration === 0);
  35598. }
  35599. for (var i = 0; i < _this.triangles.length; ++i) {
  35600. _this.triangles[i].isDirty = false;
  35601. }
  35602. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  35603. var trianglesIterator = function (i) {
  35604. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  35605. var t = _this.triangles[tIdx];
  35606. if (!t)
  35607. return;
  35608. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  35609. return;
  35610. }
  35611. for (var j = 0; j < 3; ++j) {
  35612. if (t.error[j] < threshold) {
  35613. var deleted0 = [];
  35614. var deleted1 = [];
  35615. var v0 = t.vertices[j];
  35616. var v1 = t.vertices[(j + 1) % 3];
  35617. if (v0.isBorder || v1.isBorder)
  35618. continue;
  35619. var p = BABYLON.Vector3.Zero();
  35620. var n = BABYLON.Vector3.Zero();
  35621. var uv = BABYLON.Vector2.Zero();
  35622. var color = new BABYLON.Color4(0, 0, 0, 1);
  35623. _this.calculateError(v0, v1, p, n, uv, color);
  35624. var delTr = [];
  35625. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  35626. continue;
  35627. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  35628. continue;
  35629. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  35630. continue;
  35631. var uniqueArray = [];
  35632. delTr.forEach(function (deletedT) {
  35633. if (uniqueArray.indexOf(deletedT) === -1) {
  35634. deletedT.deletePending = true;
  35635. uniqueArray.push(deletedT);
  35636. }
  35637. });
  35638. if (uniqueArray.length % 2 !== 0) {
  35639. continue;
  35640. }
  35641. v0.q = v1.q.add(v0.q);
  35642. v0.updatePosition(p);
  35643. var tStart = _this.references.length;
  35644. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  35645. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  35646. var tCount = _this.references.length - tStart;
  35647. if (tCount <= v0.triangleCount) {
  35648. if (tCount) {
  35649. for (var c = 0; c < tCount; c++) {
  35650. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  35651. }
  35652. }
  35653. }
  35654. else {
  35655. v0.triangleStart = tStart;
  35656. }
  35657. v0.triangleCount = tCount;
  35658. break;
  35659. }
  35660. }
  35661. };
  35662. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  35663. }, 0);
  35664. };
  35665. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  35666. if (triangleCount - deletedTriangles <= targetCount)
  35667. loop.breakLoop();
  35668. else {
  35669. iterationFunction(loop.index, function () {
  35670. loop.executeNext();
  35671. });
  35672. }
  35673. }, function () {
  35674. setTimeout(function () {
  35675. //reconstruct this part of the mesh
  35676. _this.reconstructMesh(submeshIndex);
  35677. successCallback();
  35678. }, 0);
  35679. });
  35680. };
  35681. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  35682. var _this = this;
  35683. this.vertices = [];
  35684. this.triangles = [];
  35685. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35686. var indices = this._mesh.getIndices();
  35687. var submesh = this._mesh.subMeshes[submeshIndex];
  35688. var findInVertices = function (positionToSearch) {
  35689. if (optimizeMesh) {
  35690. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  35691. if (_this.vertices[ii].position.equals(positionToSearch)) {
  35692. return _this.vertices[ii];
  35693. }
  35694. }
  35695. }
  35696. return null;
  35697. };
  35698. var vertexReferences = [];
  35699. var vertexInit = function (i) {
  35700. var offset = i + submesh.verticesStart;
  35701. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  35702. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  35703. vertex.originalOffsets.push(offset);
  35704. if (vertex.id === _this.vertices.length) {
  35705. _this.vertices.push(vertex);
  35706. }
  35707. vertexReferences.push(vertex.id);
  35708. };
  35709. //var totalVertices = mesh.getTotalVertices();
  35710. var totalVertices = submesh.verticesCount;
  35711. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  35712. var indicesInit = function (i) {
  35713. var offset = (submesh.indexStart / 3) + i;
  35714. var pos = (offset * 3);
  35715. var i0 = indices[pos + 0];
  35716. var i1 = indices[pos + 1];
  35717. var i2 = indices[pos + 2];
  35718. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  35719. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  35720. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  35721. var triangle = new DecimationTriangle([v0, v1, v2]);
  35722. triangle.originalOffset = pos;
  35723. _this.triangles.push(triangle);
  35724. };
  35725. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  35726. _this.init(callback);
  35727. });
  35728. });
  35729. };
  35730. QuadraticErrorSimplification.prototype.init = function (callback) {
  35731. var _this = this;
  35732. var triangleInit1 = function (i) {
  35733. var t = _this.triangles[i];
  35734. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  35735. for (var j = 0; j < 3; j++) {
  35736. 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))));
  35737. }
  35738. };
  35739. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  35740. var triangleInit2 = function (i) {
  35741. var t = _this.triangles[i];
  35742. for (var j = 0; j < 3; ++j) {
  35743. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  35744. }
  35745. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35746. };
  35747. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  35748. _this.initialized = true;
  35749. callback();
  35750. });
  35751. });
  35752. };
  35753. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  35754. var newTriangles = [];
  35755. var i;
  35756. for (i = 0; i < this.vertices.length; ++i) {
  35757. this.vertices[i].triangleCount = 0;
  35758. }
  35759. var t;
  35760. var j;
  35761. for (i = 0; i < this.triangles.length; ++i) {
  35762. if (!this.triangles[i].deleted) {
  35763. t = this.triangles[i];
  35764. for (j = 0; j < 3; ++j) {
  35765. t.vertices[j].triangleCount = 1;
  35766. }
  35767. newTriangles.push(t);
  35768. }
  35769. }
  35770. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  35771. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  35772. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  35773. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  35774. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35775. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35776. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35777. var vertexCount = 0;
  35778. for (i = 0; i < this.vertices.length; ++i) {
  35779. var vertex = this.vertices[i];
  35780. vertex.id = vertexCount;
  35781. if (vertex.triangleCount) {
  35782. vertex.originalOffsets.forEach(function (originalOffset) {
  35783. newPositionData.push(vertex.position.x);
  35784. newPositionData.push(vertex.position.y);
  35785. newPositionData.push(vertex.position.z);
  35786. newNormalData.push(normalData[originalOffset * 3]);
  35787. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  35788. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  35789. if (uvs && uvs.length) {
  35790. newUVsData.push(uvs[(originalOffset * 2)]);
  35791. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  35792. }
  35793. else if (colorsData && colorsData.length) {
  35794. newColorsData.push(colorsData[(originalOffset * 4)]);
  35795. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  35796. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  35797. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  35798. }
  35799. ++vertexCount;
  35800. });
  35801. }
  35802. }
  35803. var startingIndex = this._reconstructedMesh.getTotalIndices();
  35804. var startingVertex = this._reconstructedMesh.getTotalVertices();
  35805. var submeshesArray = this._reconstructedMesh.subMeshes;
  35806. this._reconstructedMesh.subMeshes = [];
  35807. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  35808. var originalIndices = this._mesh.getIndices();
  35809. for (i = 0; i < newTriangles.length; ++i) {
  35810. t = newTriangles[i]; //now get the new referencing point for each vertex
  35811. [0, 1, 2].forEach(function (idx) {
  35812. var id = originalIndices[t.originalOffset + idx];
  35813. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  35814. if (offset < 0)
  35815. offset = 0;
  35816. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  35817. });
  35818. }
  35819. //overwriting the old vertex buffers and indices.
  35820. this._reconstructedMesh.setIndices(newIndicesArray);
  35821. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  35822. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  35823. if (newUVsData.length > 0)
  35824. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  35825. if (newColorsData.length > 0)
  35826. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  35827. //create submesh
  35828. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  35829. if (submeshIndex > 0) {
  35830. this._reconstructedMesh.subMeshes = [];
  35831. submeshesArray.forEach(function (submesh) {
  35832. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  35833. });
  35834. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  35835. }
  35836. };
  35837. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  35838. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  35839. this._reconstructedMesh.material = this._mesh.material;
  35840. this._reconstructedMesh.parent = this._mesh.parent;
  35841. this._reconstructedMesh.isVisible = false;
  35842. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  35843. };
  35844. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  35845. for (var i = 0; i < vertex1.triangleCount; ++i) {
  35846. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  35847. if (t.deleted)
  35848. continue;
  35849. var s = this.references[vertex1.triangleStart + i].vertexId;
  35850. var v1 = t.vertices[(s + 1) % 3];
  35851. var v2 = t.vertices[(s + 2) % 3];
  35852. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  35853. deletedArray[i] = true;
  35854. delTr.push(t);
  35855. continue;
  35856. }
  35857. var d1 = v1.position.subtract(point);
  35858. d1 = d1.normalize();
  35859. var d2 = v2.position.subtract(point);
  35860. d2 = d2.normalize();
  35861. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  35862. return true;
  35863. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  35864. deletedArray[i] = false;
  35865. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  35866. return true;
  35867. }
  35868. return false;
  35869. };
  35870. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  35871. var newDeleted = deletedTriangles;
  35872. for (var i = 0; i < vertex.triangleCount; ++i) {
  35873. var ref = this.references[vertex.triangleStart + i];
  35874. var t = this.triangles[ref.triangleId];
  35875. if (t.deleted)
  35876. continue;
  35877. if (deletedArray[i] && t.deletePending) {
  35878. t.deleted = true;
  35879. newDeleted++;
  35880. continue;
  35881. }
  35882. t.vertices[ref.vertexId] = origVertex;
  35883. t.isDirty = true;
  35884. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  35885. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  35886. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  35887. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35888. this.references.push(ref);
  35889. }
  35890. return newDeleted;
  35891. };
  35892. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  35893. for (var i = 0; i < this.vertices.length; ++i) {
  35894. var vCount = [];
  35895. var vId = [];
  35896. var v = this.vertices[i];
  35897. var j;
  35898. for (j = 0; j < v.triangleCount; ++j) {
  35899. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  35900. for (var ii = 0; ii < 3; ii++) {
  35901. var ofs = 0;
  35902. var vv = triangle.vertices[ii];
  35903. while (ofs < vCount.length) {
  35904. if (vId[ofs] === vv.id)
  35905. break;
  35906. ++ofs;
  35907. }
  35908. if (ofs === vCount.length) {
  35909. vCount.push(1);
  35910. vId.push(vv.id);
  35911. }
  35912. else {
  35913. vCount[ofs]++;
  35914. }
  35915. }
  35916. }
  35917. for (j = 0; j < vCount.length; ++j) {
  35918. if (vCount[j] === 1) {
  35919. this.vertices[vId[j]].isBorder = true;
  35920. }
  35921. else {
  35922. this.vertices[vId[j]].isBorder = false;
  35923. }
  35924. }
  35925. }
  35926. };
  35927. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  35928. if (identifyBorders === void 0) { identifyBorders = false; }
  35929. var i;
  35930. if (!identifyBorders) {
  35931. var newTrianglesVector = [];
  35932. for (i = 0; i < this.triangles.length; ++i) {
  35933. if (!this.triangles[i].deleted) {
  35934. newTrianglesVector.push(this.triangles[i]);
  35935. }
  35936. }
  35937. this.triangles = newTrianglesVector;
  35938. }
  35939. for (i = 0; i < this.vertices.length; ++i) {
  35940. this.vertices[i].triangleCount = 0;
  35941. this.vertices[i].triangleStart = 0;
  35942. }
  35943. var t;
  35944. var j;
  35945. var v;
  35946. for (i = 0; i < this.triangles.length; ++i) {
  35947. t = this.triangles[i];
  35948. for (j = 0; j < 3; ++j) {
  35949. v = t.vertices[j];
  35950. v.triangleCount++;
  35951. }
  35952. }
  35953. var tStart = 0;
  35954. for (i = 0; i < this.vertices.length; ++i) {
  35955. this.vertices[i].triangleStart = tStart;
  35956. tStart += this.vertices[i].triangleCount;
  35957. this.vertices[i].triangleCount = 0;
  35958. }
  35959. var newReferences = new Array(this.triangles.length * 3);
  35960. for (i = 0; i < this.triangles.length; ++i) {
  35961. t = this.triangles[i];
  35962. for (j = 0; j < 3; ++j) {
  35963. v = t.vertices[j];
  35964. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  35965. v.triangleCount++;
  35966. }
  35967. }
  35968. this.references = newReferences;
  35969. if (identifyBorders) {
  35970. this.identifyBorder();
  35971. }
  35972. };
  35973. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  35974. var x = point.x;
  35975. var y = point.y;
  35976. var z = point.z;
  35977. 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
  35978. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  35979. };
  35980. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  35981. var q = vertex1.q.add(vertex2.q);
  35982. var border = vertex1.isBorder && vertex2.isBorder;
  35983. var error = 0;
  35984. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  35985. if (qDet !== 0 && !border) {
  35986. if (!pointResult) {
  35987. pointResult = BABYLON.Vector3.Zero();
  35988. }
  35989. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  35990. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  35991. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  35992. error = this.vertexError(q, pointResult);
  35993. }
  35994. else {
  35995. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  35996. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  35997. var error1 = this.vertexError(q, vertex1.position);
  35998. var error2 = this.vertexError(q, vertex2.position);
  35999. var error3 = this.vertexError(q, p3);
  36000. error = Math.min(error1, error2, error3);
  36001. if (error === error1) {
  36002. if (pointResult) {
  36003. pointResult.copyFrom(vertex1.position);
  36004. }
  36005. }
  36006. else if (error === error2) {
  36007. if (pointResult) {
  36008. pointResult.copyFrom(vertex2.position);
  36009. }
  36010. }
  36011. else {
  36012. if (pointResult) {
  36013. pointResult.copyFrom(p3);
  36014. }
  36015. }
  36016. }
  36017. return error;
  36018. };
  36019. return QuadraticErrorSimplification;
  36020. })();
  36021. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  36022. })(BABYLON || (BABYLON = {}));
  36023. var BABYLON;
  36024. (function (BABYLON) {
  36025. var serializedGeometries = [];
  36026. var serializeGeometry = function (geometry, serializationGeometries) {
  36027. if (serializedGeometries[geometry.id]) {
  36028. return;
  36029. }
  36030. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  36031. serializationGeometries.boxes.push(geometry.serialize());
  36032. }
  36033. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  36034. serializationGeometries.spheres.push(geometry.serialize());
  36035. }
  36036. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  36037. serializationGeometries.cylinders.push(geometry.serialize());
  36038. }
  36039. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  36040. serializationGeometries.toruses.push(geometry.serialize());
  36041. }
  36042. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  36043. serializationGeometries.grounds.push(geometry.serialize());
  36044. }
  36045. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  36046. serializationGeometries.planes.push(geometry.serialize());
  36047. }
  36048. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  36049. serializationGeometries.torusKnots.push(geometry.serialize());
  36050. }
  36051. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  36052. throw new Error("Unknown primitive type");
  36053. }
  36054. else {
  36055. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  36056. }
  36057. serializedGeometries[geometry.id] = true;
  36058. };
  36059. var serializeMesh = function (mesh, serializationScene) {
  36060. var serializationObject = {};
  36061. serializationObject.name = mesh.name;
  36062. serializationObject.id = mesh.id;
  36063. if (BABYLON.Tags.HasTags(mesh)) {
  36064. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  36065. }
  36066. serializationObject.position = mesh.position.asArray();
  36067. if (mesh.rotationQuaternion) {
  36068. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  36069. }
  36070. else if (mesh.rotation) {
  36071. serializationObject.rotation = mesh.rotation.asArray();
  36072. }
  36073. serializationObject.scaling = mesh.scaling.asArray();
  36074. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  36075. serializationObject.isEnabled = mesh.isEnabled();
  36076. serializationObject.isVisible = mesh.isVisible;
  36077. serializationObject.infiniteDistance = mesh.infiniteDistance;
  36078. serializationObject.pickable = mesh.isPickable;
  36079. serializationObject.receiveShadows = mesh.receiveShadows;
  36080. serializationObject.billboardMode = mesh.billboardMode;
  36081. serializationObject.visibility = mesh.visibility;
  36082. serializationObject.checkCollisions = mesh.checkCollisions;
  36083. // Parent
  36084. if (mesh.parent) {
  36085. serializationObject.parentId = mesh.parent.id;
  36086. }
  36087. // Geometry
  36088. var geometry = mesh._geometry;
  36089. if (geometry) {
  36090. var geometryId = geometry.id;
  36091. serializationObject.geometryId = geometryId;
  36092. if (!mesh.getScene().getGeometryByID(geometryId)) {
  36093. // 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
  36094. serializeGeometry(geometry, serializationScene.geometries);
  36095. }
  36096. // SubMeshes
  36097. serializationObject.subMeshes = [];
  36098. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36099. var subMesh = mesh.subMeshes[subIndex];
  36100. serializationObject.subMeshes.push({
  36101. materialIndex: subMesh.materialIndex,
  36102. verticesStart: subMesh.verticesStart,
  36103. verticesCount: subMesh.verticesCount,
  36104. indexStart: subMesh.indexStart,
  36105. indexCount: subMesh.indexCount
  36106. });
  36107. }
  36108. }
  36109. // Material
  36110. if (mesh.material) {
  36111. serializationObject.materialId = mesh.material.id;
  36112. }
  36113. else {
  36114. mesh.material = null;
  36115. }
  36116. // Skeleton
  36117. if (mesh.skeleton) {
  36118. serializationObject.skeletonId = mesh.skeleton.id;
  36119. }
  36120. // Physics
  36121. //TODO implement correct serialization for physics impostors.
  36122. if (mesh.getPhysicsImpostor()) {
  36123. serializationObject.physicsMass = mesh.getPhysicsMass();
  36124. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  36125. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  36126. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  36127. }
  36128. // Instances
  36129. serializationObject.instances = [];
  36130. for (var index = 0; index < mesh.instances.length; index++) {
  36131. var instance = mesh.instances[index];
  36132. var serializationInstance = {
  36133. name: instance.name,
  36134. position: instance.position.asArray(),
  36135. scaling: instance.scaling.asArray()
  36136. };
  36137. if (instance.rotationQuaternion) {
  36138. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  36139. }
  36140. else if (instance.rotation) {
  36141. serializationInstance.rotation = instance.rotation.asArray();
  36142. }
  36143. serializationObject.instances.push(serializationInstance);
  36144. // Animations
  36145. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  36146. serializationInstance.ranges = instance.serializeAnimationRanges();
  36147. }
  36148. // Animations
  36149. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  36150. serializationObject.ranges = mesh.serializeAnimationRanges();
  36151. // Layer mask
  36152. serializationObject.layerMask = mesh.layerMask;
  36153. return serializationObject;
  36154. };
  36155. var finalizeSingleMesh = function (mesh, serializationObject) {
  36156. //only works if the mesh is already loaded
  36157. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36158. //serialize material
  36159. if (mesh.material) {
  36160. if (mesh.material instanceof BABYLON.StandardMaterial) {
  36161. serializationObject.materials = serializationObject.materials || [];
  36162. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36163. serializationObject.materials.push(mesh.material.serialize());
  36164. }
  36165. }
  36166. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  36167. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  36168. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36169. serializationObject.multiMaterials.push(mesh.material.serialize());
  36170. }
  36171. }
  36172. }
  36173. //serialize geometry
  36174. var geometry = mesh._geometry;
  36175. if (geometry) {
  36176. if (!serializationObject.geometries) {
  36177. serializationObject.geometries = {};
  36178. serializationObject.geometries.boxes = [];
  36179. serializationObject.geometries.spheres = [];
  36180. serializationObject.geometries.cylinders = [];
  36181. serializationObject.geometries.toruses = [];
  36182. serializationObject.geometries.grounds = [];
  36183. serializationObject.geometries.planes = [];
  36184. serializationObject.geometries.torusKnots = [];
  36185. serializationObject.geometries.vertexData = [];
  36186. }
  36187. serializeGeometry(geometry, serializationObject.geometries);
  36188. }
  36189. // Skeletons
  36190. if (mesh.skeleton) {
  36191. serializationObject.skeletons = serializationObject.skeletons || [];
  36192. serializationObject.skeletons.push(mesh.skeleton.serialize());
  36193. }
  36194. //serialize the actual mesh
  36195. serializationObject.meshes = serializationObject.meshes || [];
  36196. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36197. }
  36198. };
  36199. var SceneSerializer = (function () {
  36200. function SceneSerializer() {
  36201. }
  36202. SceneSerializer.ClearCache = function () {
  36203. serializedGeometries = [];
  36204. };
  36205. SceneSerializer.Serialize = function (scene) {
  36206. var serializationObject = {};
  36207. // Scene
  36208. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  36209. serializationObject.autoClear = scene.autoClear;
  36210. serializationObject.clearColor = scene.clearColor.asArray();
  36211. serializationObject.ambientColor = scene.ambientColor.asArray();
  36212. serializationObject.gravity = scene.gravity.asArray();
  36213. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  36214. serializationObject.workerCollisions = scene.workerCollisions;
  36215. // Fog
  36216. if (scene.fogMode && scene.fogMode !== 0) {
  36217. serializationObject.fogMode = scene.fogMode;
  36218. serializationObject.fogColor = scene.fogColor.asArray();
  36219. serializationObject.fogStart = scene.fogStart;
  36220. serializationObject.fogEnd = scene.fogEnd;
  36221. serializationObject.fogDensity = scene.fogDensity;
  36222. }
  36223. //Physics
  36224. if (scene.isPhysicsEnabled()) {
  36225. serializationObject.physicsEnabled = true;
  36226. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  36227. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  36228. }
  36229. // Lights
  36230. serializationObject.lights = [];
  36231. var index;
  36232. var light;
  36233. for (index = 0; index < scene.lights.length; index++) {
  36234. light = scene.lights[index];
  36235. serializationObject.lights.push(light.serialize());
  36236. }
  36237. // Cameras
  36238. serializationObject.cameras = [];
  36239. for (index = 0; index < scene.cameras.length; index++) {
  36240. var camera = scene.cameras[index];
  36241. serializationObject.cameras.push(camera.serialize());
  36242. }
  36243. if (scene.activeCamera) {
  36244. serializationObject.activeCameraID = scene.activeCamera.id;
  36245. }
  36246. // Animations
  36247. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  36248. // Materials
  36249. serializationObject.materials = [];
  36250. serializationObject.multiMaterials = [];
  36251. var material;
  36252. for (index = 0; index < scene.materials.length; index++) {
  36253. material = scene.materials[index];
  36254. serializationObject.materials.push(material.serialize());
  36255. }
  36256. // MultiMaterials
  36257. serializationObject.multiMaterials = [];
  36258. for (index = 0; index < scene.multiMaterials.length; index++) {
  36259. var multiMaterial = scene.multiMaterials[index];
  36260. serializationObject.multiMaterials.push(multiMaterial.serialize());
  36261. }
  36262. // Skeletons
  36263. serializationObject.skeletons = [];
  36264. for (index = 0; index < scene.skeletons.length; index++) {
  36265. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  36266. }
  36267. // Geometries
  36268. serializationObject.geometries = {};
  36269. serializationObject.geometries.boxes = [];
  36270. serializationObject.geometries.spheres = [];
  36271. serializationObject.geometries.cylinders = [];
  36272. serializationObject.geometries.toruses = [];
  36273. serializationObject.geometries.grounds = [];
  36274. serializationObject.geometries.planes = [];
  36275. serializationObject.geometries.torusKnots = [];
  36276. serializationObject.geometries.vertexData = [];
  36277. serializedGeometries = [];
  36278. var geometries = scene.getGeometries();
  36279. for (index = 0; index < geometries.length; index++) {
  36280. var geometry = geometries[index];
  36281. if (geometry.isReady()) {
  36282. serializeGeometry(geometry, serializationObject.geometries);
  36283. }
  36284. }
  36285. // Meshes
  36286. serializationObject.meshes = [];
  36287. for (index = 0; index < scene.meshes.length; index++) {
  36288. var abstractMesh = scene.meshes[index];
  36289. if (abstractMesh instanceof BABYLON.Mesh) {
  36290. var mesh = abstractMesh;
  36291. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36292. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36293. }
  36294. }
  36295. }
  36296. // Particles Systems
  36297. serializationObject.particleSystems = [];
  36298. for (index = 0; index < scene.particleSystems.length; index++) {
  36299. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  36300. }
  36301. // Lens flares
  36302. serializationObject.lensFlareSystems = [];
  36303. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  36304. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  36305. }
  36306. // Shadows
  36307. serializationObject.shadowGenerators = [];
  36308. for (index = 0; index < scene.lights.length; index++) {
  36309. light = scene.lights[index];
  36310. if (light.getShadowGenerator()) {
  36311. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  36312. }
  36313. }
  36314. return serializationObject;
  36315. };
  36316. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  36317. if (withParents === void 0) { withParents = false; }
  36318. if (withChildren === void 0) { withChildren = false; }
  36319. var serializationObject = {};
  36320. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  36321. if (withParents || withChildren) {
  36322. //deliberate for loop! not for each, appended should be processed as well.
  36323. for (var i = 0; i < toSerialize.length; ++i) {
  36324. if (withChildren) {
  36325. toSerialize[i].getDescendants().forEach(function (node) {
  36326. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  36327. toSerialize.push(node);
  36328. }
  36329. });
  36330. }
  36331. //make sure the array doesn't contain the object already
  36332. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  36333. toSerialize.push(toSerialize[i].parent);
  36334. }
  36335. }
  36336. }
  36337. toSerialize.forEach(function (mesh) {
  36338. finalizeSingleMesh(mesh, serializationObject);
  36339. });
  36340. return serializationObject;
  36341. };
  36342. return SceneSerializer;
  36343. })();
  36344. BABYLON.SceneSerializer = SceneSerializer;
  36345. })(BABYLON || (BABYLON = {}));
  36346. var BABYLON;
  36347. (function (BABYLON) {
  36348. // Unique ID when we import meshes from Babylon to CSG
  36349. var currentCSGMeshId = 0;
  36350. // # class Vertex
  36351. // Represents a vertex of a polygon. Use your own vertex class instead of this
  36352. // one to provide additional features like texture coordinates and vertex
  36353. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  36354. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  36355. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  36356. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  36357. // is not used anywhere else.
  36358. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  36359. var Vertex = (function () {
  36360. function Vertex(pos, normal, uv) {
  36361. this.pos = pos;
  36362. this.normal = normal;
  36363. this.uv = uv;
  36364. }
  36365. Vertex.prototype.clone = function () {
  36366. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  36367. };
  36368. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  36369. // orientation of a polygon is flipped.
  36370. Vertex.prototype.flip = function () {
  36371. this.normal = this.normal.scale(-1);
  36372. };
  36373. // Create a new vertex between this vertex and `other` by linearly
  36374. // interpolating all properties using a parameter of `t`. Subclasses should
  36375. // override this to interpolate additional properties.
  36376. Vertex.prototype.interpolate = function (other, t) {
  36377. 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));
  36378. };
  36379. return Vertex;
  36380. })();
  36381. // # class Plane
  36382. // Represents a plane in 3D space.
  36383. var Plane = (function () {
  36384. function Plane(normal, w) {
  36385. this.normal = normal;
  36386. this.w = w;
  36387. }
  36388. Plane.FromPoints = function (a, b, c) {
  36389. var v0 = c.subtract(a);
  36390. var v1 = b.subtract(a);
  36391. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  36392. return null;
  36393. }
  36394. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  36395. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  36396. };
  36397. Plane.prototype.clone = function () {
  36398. return new Plane(this.normal.clone(), this.w);
  36399. };
  36400. Plane.prototype.flip = function () {
  36401. this.normal.scaleInPlace(-1);
  36402. this.w = -this.w;
  36403. };
  36404. // Split `polygon` by this plane if needed, then put the polygon or polygon
  36405. // fragments in the appropriate lists. Coplanar polygons go into either
  36406. // `coplanarFront` or `coplanarBack` depending on their orientation with
  36407. // respect to this plane. Polygons in front or in back of this plane go into
  36408. // either `front` or `back`.
  36409. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  36410. var COPLANAR = 0;
  36411. var FRONT = 1;
  36412. var BACK = 2;
  36413. var SPANNING = 3;
  36414. // Classify each point as well as the entire polygon into one of the above
  36415. // four classes.
  36416. var polygonType = 0;
  36417. var types = [];
  36418. var i;
  36419. var t;
  36420. for (i = 0; i < polygon.vertices.length; i++) {
  36421. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  36422. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  36423. polygonType |= type;
  36424. types.push(type);
  36425. }
  36426. // Put the polygon in the correct list, splitting it when necessary.
  36427. switch (polygonType) {
  36428. case COPLANAR:
  36429. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  36430. break;
  36431. case FRONT:
  36432. front.push(polygon);
  36433. break;
  36434. case BACK:
  36435. back.push(polygon);
  36436. break;
  36437. case SPANNING:
  36438. var f = [], b = [];
  36439. for (i = 0; i < polygon.vertices.length; i++) {
  36440. var j = (i + 1) % polygon.vertices.length;
  36441. var ti = types[i], tj = types[j];
  36442. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  36443. if (ti !== BACK)
  36444. f.push(vi);
  36445. if (ti !== FRONT)
  36446. b.push(ti !== BACK ? vi.clone() : vi);
  36447. if ((ti | tj) === SPANNING) {
  36448. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  36449. var v = vi.interpolate(vj, t);
  36450. f.push(v);
  36451. b.push(v.clone());
  36452. }
  36453. }
  36454. var poly;
  36455. if (f.length >= 3) {
  36456. poly = new Polygon(f, polygon.shared);
  36457. if (poly.plane)
  36458. front.push(poly);
  36459. }
  36460. if (b.length >= 3) {
  36461. poly = new Polygon(b, polygon.shared);
  36462. if (poly.plane)
  36463. back.push(poly);
  36464. }
  36465. break;
  36466. }
  36467. };
  36468. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  36469. // point is on the plane.
  36470. Plane.EPSILON = 1e-5;
  36471. return Plane;
  36472. })();
  36473. // # class Polygon
  36474. // Represents a convex polygon. The vertices used to initialize a polygon must
  36475. // be coplanar and form a convex loop.
  36476. //
  36477. // Each convex polygon has a `shared` property, which is shared between all
  36478. // polygons that are clones of each other or were split from the same polygon.
  36479. // This can be used to define per-polygon properties (such as surface color).
  36480. var Polygon = (function () {
  36481. function Polygon(vertices, shared) {
  36482. this.vertices = vertices;
  36483. this.shared = shared;
  36484. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  36485. }
  36486. Polygon.prototype.clone = function () {
  36487. var vertices = this.vertices.map(function (v) { return v.clone(); });
  36488. return new Polygon(vertices, this.shared);
  36489. };
  36490. Polygon.prototype.flip = function () {
  36491. this.vertices.reverse().map(function (v) { v.flip(); });
  36492. this.plane.flip();
  36493. };
  36494. return Polygon;
  36495. })();
  36496. // # class Node
  36497. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  36498. // by picking a polygon to split along. That polygon (and all other coplanar
  36499. // polygons) are added directly to that node and the other polygons are added to
  36500. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  36501. // no distinction between internal and leaf nodes.
  36502. var Node = (function () {
  36503. function Node(polygons) {
  36504. this.plane = null;
  36505. this.front = null;
  36506. this.back = null;
  36507. this.polygons = [];
  36508. if (polygons) {
  36509. this.build(polygons);
  36510. }
  36511. }
  36512. Node.prototype.clone = function () {
  36513. var node = new Node();
  36514. node.plane = this.plane && this.plane.clone();
  36515. node.front = this.front && this.front.clone();
  36516. node.back = this.back && this.back.clone();
  36517. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  36518. return node;
  36519. };
  36520. // Convert solid space to empty space and empty space to solid space.
  36521. Node.prototype.invert = function () {
  36522. for (var i = 0; i < this.polygons.length; i++) {
  36523. this.polygons[i].flip();
  36524. }
  36525. if (this.plane) {
  36526. this.plane.flip();
  36527. }
  36528. if (this.front) {
  36529. this.front.invert();
  36530. }
  36531. if (this.back) {
  36532. this.back.invert();
  36533. }
  36534. var temp = this.front;
  36535. this.front = this.back;
  36536. this.back = temp;
  36537. };
  36538. // Recursively remove all polygons in `polygons` that are inside this BSP
  36539. // tree.
  36540. Node.prototype.clipPolygons = function (polygons) {
  36541. if (!this.plane)
  36542. return polygons.slice();
  36543. var front = [], back = [];
  36544. for (var i = 0; i < polygons.length; i++) {
  36545. this.plane.splitPolygon(polygons[i], front, back, front, back);
  36546. }
  36547. if (this.front) {
  36548. front = this.front.clipPolygons(front);
  36549. }
  36550. if (this.back) {
  36551. back = this.back.clipPolygons(back);
  36552. }
  36553. else {
  36554. back = [];
  36555. }
  36556. return front.concat(back);
  36557. };
  36558. // Remove all polygons in this BSP tree that are inside the other BSP tree
  36559. // `bsp`.
  36560. Node.prototype.clipTo = function (bsp) {
  36561. this.polygons = bsp.clipPolygons(this.polygons);
  36562. if (this.front)
  36563. this.front.clipTo(bsp);
  36564. if (this.back)
  36565. this.back.clipTo(bsp);
  36566. };
  36567. // Return a list of all polygons in this BSP tree.
  36568. Node.prototype.allPolygons = function () {
  36569. var polygons = this.polygons.slice();
  36570. if (this.front)
  36571. polygons = polygons.concat(this.front.allPolygons());
  36572. if (this.back)
  36573. polygons = polygons.concat(this.back.allPolygons());
  36574. return polygons;
  36575. };
  36576. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  36577. // new polygons are filtered down to the bottom of the tree and become new
  36578. // nodes there. Each set of polygons is partitioned using the first polygon
  36579. // (no heuristic is used to pick a good split).
  36580. Node.prototype.build = function (polygons) {
  36581. if (!polygons.length)
  36582. return;
  36583. if (!this.plane)
  36584. this.plane = polygons[0].plane.clone();
  36585. var front = [], back = [];
  36586. for (var i = 0; i < polygons.length; i++) {
  36587. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  36588. }
  36589. if (front.length) {
  36590. if (!this.front)
  36591. this.front = new Node();
  36592. this.front.build(front);
  36593. }
  36594. if (back.length) {
  36595. if (!this.back)
  36596. this.back = new Node();
  36597. this.back.build(back);
  36598. }
  36599. };
  36600. return Node;
  36601. })();
  36602. var CSG = (function () {
  36603. function CSG() {
  36604. this.polygons = new Array();
  36605. }
  36606. // Convert BABYLON.Mesh to BABYLON.CSG
  36607. CSG.FromMesh = function (mesh) {
  36608. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  36609. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  36610. if (mesh instanceof BABYLON.Mesh) {
  36611. mesh.computeWorldMatrix(true);
  36612. matrix = mesh.getWorldMatrix();
  36613. meshPosition = mesh.position.clone();
  36614. meshRotation = mesh.rotation.clone();
  36615. if (mesh.rotationQuaternion) {
  36616. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  36617. }
  36618. meshScaling = mesh.scaling.clone();
  36619. }
  36620. else {
  36621. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  36622. }
  36623. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36624. var subMeshes = mesh.subMeshes;
  36625. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  36626. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  36627. vertices = [];
  36628. for (var j = 0; j < 3; j++) {
  36629. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  36630. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  36631. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  36632. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  36633. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  36634. vertex = new Vertex(position, normal, uv);
  36635. vertices.push(vertex);
  36636. }
  36637. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  36638. // To handle the case of degenerated triangle
  36639. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  36640. if (polygon.plane)
  36641. polygons.push(polygon);
  36642. }
  36643. }
  36644. var csg = CSG.FromPolygons(polygons);
  36645. csg.matrix = matrix;
  36646. csg.position = meshPosition;
  36647. csg.rotation = meshRotation;
  36648. csg.scaling = meshScaling;
  36649. csg.rotationQuaternion = meshRotationQuaternion;
  36650. currentCSGMeshId++;
  36651. return csg;
  36652. };
  36653. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  36654. CSG.FromPolygons = function (polygons) {
  36655. var csg = new CSG();
  36656. csg.polygons = polygons;
  36657. return csg;
  36658. };
  36659. CSG.prototype.clone = function () {
  36660. var csg = new CSG();
  36661. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  36662. csg.copyTransformAttributes(this);
  36663. return csg;
  36664. };
  36665. CSG.prototype.toPolygons = function () {
  36666. return this.polygons;
  36667. };
  36668. CSG.prototype.union = function (csg) {
  36669. var a = new Node(this.clone().polygons);
  36670. var b = new Node(csg.clone().polygons);
  36671. a.clipTo(b);
  36672. b.clipTo(a);
  36673. b.invert();
  36674. b.clipTo(a);
  36675. b.invert();
  36676. a.build(b.allPolygons());
  36677. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36678. };
  36679. CSG.prototype.unionInPlace = function (csg) {
  36680. var a = new Node(this.polygons);
  36681. var b = new Node(csg.polygons);
  36682. a.clipTo(b);
  36683. b.clipTo(a);
  36684. b.invert();
  36685. b.clipTo(a);
  36686. b.invert();
  36687. a.build(b.allPolygons());
  36688. this.polygons = a.allPolygons();
  36689. };
  36690. CSG.prototype.subtract = function (csg) {
  36691. var a = new Node(this.clone().polygons);
  36692. var b = new Node(csg.clone().polygons);
  36693. a.invert();
  36694. a.clipTo(b);
  36695. b.clipTo(a);
  36696. b.invert();
  36697. b.clipTo(a);
  36698. b.invert();
  36699. a.build(b.allPolygons());
  36700. a.invert();
  36701. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36702. };
  36703. CSG.prototype.subtractInPlace = function (csg) {
  36704. var a = new Node(this.polygons);
  36705. var b = new Node(csg.polygons);
  36706. a.invert();
  36707. a.clipTo(b);
  36708. b.clipTo(a);
  36709. b.invert();
  36710. b.clipTo(a);
  36711. b.invert();
  36712. a.build(b.allPolygons());
  36713. a.invert();
  36714. this.polygons = a.allPolygons();
  36715. };
  36716. CSG.prototype.intersect = function (csg) {
  36717. var a = new Node(this.clone().polygons);
  36718. var b = new Node(csg.clone().polygons);
  36719. a.invert();
  36720. b.clipTo(a);
  36721. b.invert();
  36722. a.clipTo(b);
  36723. b.clipTo(a);
  36724. a.build(b.allPolygons());
  36725. a.invert();
  36726. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36727. };
  36728. CSG.prototype.intersectInPlace = function (csg) {
  36729. var a = new Node(this.polygons);
  36730. var b = new Node(csg.polygons);
  36731. a.invert();
  36732. b.clipTo(a);
  36733. b.invert();
  36734. a.clipTo(b);
  36735. b.clipTo(a);
  36736. a.build(b.allPolygons());
  36737. a.invert();
  36738. this.polygons = a.allPolygons();
  36739. };
  36740. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  36741. // not modified.
  36742. CSG.prototype.inverse = function () {
  36743. var csg = this.clone();
  36744. csg.inverseInPlace();
  36745. return csg;
  36746. };
  36747. CSG.prototype.inverseInPlace = function () {
  36748. this.polygons.map(function (p) { p.flip(); });
  36749. };
  36750. // This is used to keep meshes transformations so they can be restored
  36751. // when we build back a Babylon Mesh
  36752. // NB : All CSG operations are performed in world coordinates
  36753. CSG.prototype.copyTransformAttributes = function (csg) {
  36754. this.matrix = csg.matrix;
  36755. this.position = csg.position;
  36756. this.rotation = csg.rotation;
  36757. this.scaling = csg.scaling;
  36758. this.rotationQuaternion = csg.rotationQuaternion;
  36759. return this;
  36760. };
  36761. // Build Raw mesh from CSG
  36762. // Coordinates here are in world space
  36763. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  36764. var matrix = this.matrix.clone();
  36765. matrix.invert();
  36766. 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;
  36767. if (keepSubMeshes) {
  36768. // Sort Polygons, since subMeshes are indices range
  36769. polygons.sort(function (a, b) {
  36770. if (a.shared.meshId === b.shared.meshId) {
  36771. return a.shared.subMeshId - b.shared.subMeshId;
  36772. }
  36773. else {
  36774. return a.shared.meshId - b.shared.meshId;
  36775. }
  36776. });
  36777. }
  36778. for (var i = 0, il = polygons.length; i < il; i++) {
  36779. polygon = polygons[i];
  36780. // Building SubMeshes
  36781. if (!subMesh_dict[polygon.shared.meshId]) {
  36782. subMesh_dict[polygon.shared.meshId] = {};
  36783. }
  36784. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  36785. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  36786. indexStart: +Infinity,
  36787. indexEnd: -Infinity,
  36788. materialIndex: polygon.shared.materialIndex
  36789. };
  36790. }
  36791. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  36792. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  36793. polygonIndices[0] = 0;
  36794. polygonIndices[1] = j - 1;
  36795. polygonIndices[2] = j;
  36796. for (var k = 0; k < 3; k++) {
  36797. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  36798. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  36799. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  36800. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  36801. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  36802. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  36803. // Check if 2 points can be merged
  36804. if (!(typeof vertex_idx !== 'undefined' &&
  36805. normals[vertex_idx * 3] === localNormal.x &&
  36806. normals[vertex_idx * 3 + 1] === localNormal.y &&
  36807. normals[vertex_idx * 3 + 2] === localNormal.z &&
  36808. uvs[vertex_idx * 2] === uv.x &&
  36809. uvs[vertex_idx * 2 + 1] === uv.y)) {
  36810. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  36811. uvs.push(uv.x, uv.y);
  36812. normals.push(normal.x, normal.y, normal.z);
  36813. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  36814. }
  36815. indices.push(vertex_idx);
  36816. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  36817. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  36818. currentIndex++;
  36819. }
  36820. }
  36821. }
  36822. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  36823. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  36824. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  36825. mesh.setIndices(indices);
  36826. if (keepSubMeshes) {
  36827. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  36828. var materialIndexOffset = 0, materialMaxIndex;
  36829. mesh.subMeshes = new Array();
  36830. for (var m in subMesh_dict) {
  36831. materialMaxIndex = -1;
  36832. for (var sm in subMesh_dict[m]) {
  36833. subMesh_obj = subMesh_dict[m][sm];
  36834. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  36835. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  36836. }
  36837. materialIndexOffset += ++materialMaxIndex;
  36838. }
  36839. }
  36840. return mesh;
  36841. };
  36842. // Build Mesh from CSG taking material and transforms into account
  36843. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  36844. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  36845. mesh.material = material;
  36846. mesh.position.copyFrom(this.position);
  36847. mesh.rotation.copyFrom(this.rotation);
  36848. if (this.rotationQuaternion) {
  36849. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  36850. }
  36851. mesh.scaling.copyFrom(this.scaling);
  36852. mesh.computeWorldMatrix(true);
  36853. return mesh;
  36854. };
  36855. return CSG;
  36856. })();
  36857. BABYLON.CSG = CSG;
  36858. })(BABYLON || (BABYLON = {}));
  36859. var BABYLON;
  36860. (function (BABYLON) {
  36861. var VRDistortionCorrectionPostProcess = (function (_super) {
  36862. __extends(VRDistortionCorrectionPostProcess, _super);
  36863. //ANY
  36864. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  36865. var _this = this;
  36866. _super.call(this, name, "vrDistortionCorrection", [
  36867. 'LensCenter',
  36868. 'Scale',
  36869. 'ScaleIn',
  36870. 'HmdWarpParam'
  36871. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  36872. this._isRightEye = isRightEye;
  36873. this._distortionFactors = vrMetrics.distortionK;
  36874. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  36875. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  36876. this.onSizeChanged = function () {
  36877. _this.aspectRatio = _this.width * .5 / _this.height;
  36878. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  36879. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  36880. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  36881. };
  36882. this.onApply = function (effect) {
  36883. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  36884. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  36885. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  36886. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  36887. };
  36888. }
  36889. return VRDistortionCorrectionPostProcess;
  36890. })(BABYLON.PostProcess);
  36891. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  36892. })(BABYLON || (BABYLON = {}));
  36893. // Mainly based on these 2 articles :
  36894. // 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
  36895. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  36896. var BABYLON;
  36897. (function (BABYLON) {
  36898. (function (JoystickAxis) {
  36899. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  36900. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  36901. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  36902. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  36903. var JoystickAxis = BABYLON.JoystickAxis;
  36904. var VirtualJoystick = (function () {
  36905. function VirtualJoystick(leftJoystick) {
  36906. var _this = this;
  36907. if (leftJoystick) {
  36908. this._leftJoystick = true;
  36909. }
  36910. else {
  36911. this._leftJoystick = false;
  36912. }
  36913. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  36914. VirtualJoystick._globalJoystickIndex++;
  36915. // By default left & right arrow keys are moving the X
  36916. // and up & down keys are moving the Y
  36917. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36918. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36919. this.reverseLeftRight = false;
  36920. this.reverseUpDown = false;
  36921. // collections of pointers
  36922. this._touches = new BABYLON.SmartCollection();
  36923. this.deltaPosition = BABYLON.Vector3.Zero();
  36924. this._joystickSensibility = 25;
  36925. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36926. this._rotationSpeed = 25;
  36927. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  36928. this._rotateOnAxisRelativeToMesh = false;
  36929. this._onResize = function (evt) {
  36930. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36931. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36932. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  36933. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  36934. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  36935. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  36936. };
  36937. // injecting a canvas element on top of the canvas 3D game
  36938. if (!VirtualJoystick.vjCanvas) {
  36939. window.addEventListener("resize", this._onResize, false);
  36940. VirtualJoystick.vjCanvas = document.createElement("canvas");
  36941. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36942. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36943. VirtualJoystick.vjCanvas.width = window.innerWidth;
  36944. VirtualJoystick.vjCanvas.height = window.innerHeight;
  36945. VirtualJoystick.vjCanvas.style.width = "100%";
  36946. VirtualJoystick.vjCanvas.style.height = "100%";
  36947. VirtualJoystick.vjCanvas.style.position = "absolute";
  36948. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  36949. VirtualJoystick.vjCanvas.style.top = "0px";
  36950. VirtualJoystick.vjCanvas.style.left = "0px";
  36951. VirtualJoystick.vjCanvas.style.zIndex = "5";
  36952. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  36953. // Support for jQuery PEP polyfill
  36954. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  36955. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  36956. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  36957. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36958. document.body.appendChild(VirtualJoystick.vjCanvas);
  36959. }
  36960. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  36961. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  36962. this.pressed = false;
  36963. // default joystick color
  36964. this._joystickColor = "cyan";
  36965. this._joystickPointerID = -1;
  36966. // current joystick position
  36967. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  36968. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  36969. // origin joystick position
  36970. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  36971. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  36972. this._onPointerDownHandlerRef = function (evt) {
  36973. _this._onPointerDown(evt);
  36974. };
  36975. this._onPointerMoveHandlerRef = function (evt) {
  36976. _this._onPointerMove(evt);
  36977. };
  36978. this._onPointerOutHandlerRef = function (evt) {
  36979. _this._onPointerUp(evt);
  36980. };
  36981. this._onPointerUpHandlerRef = function (evt) {
  36982. _this._onPointerUp(evt);
  36983. };
  36984. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  36985. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  36986. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  36987. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  36988. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  36989. evt.preventDefault(); // Disables system menu
  36990. }, false);
  36991. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36992. }
  36993. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  36994. this._joystickSensibility = newJoystickSensibility;
  36995. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36996. };
  36997. VirtualJoystick.prototype._onPointerDown = function (e) {
  36998. var positionOnScreenCondition;
  36999. e.preventDefault();
  37000. if (this._leftJoystick === true) {
  37001. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  37002. }
  37003. else {
  37004. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  37005. }
  37006. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  37007. // First contact will be dedicated to the virtual joystick
  37008. this._joystickPointerID = e.pointerId;
  37009. this._joystickPointerStartPos.x = e.clientX;
  37010. this._joystickPointerStartPos.y = e.clientY;
  37011. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  37012. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  37013. this._deltaJoystickVector.x = 0;
  37014. this._deltaJoystickVector.y = 0;
  37015. this.pressed = true;
  37016. this._touches.add(e.pointerId.toString(), e);
  37017. }
  37018. else {
  37019. // You can only trigger the action buttons with a joystick declared
  37020. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  37021. this._action();
  37022. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  37023. }
  37024. }
  37025. };
  37026. VirtualJoystick.prototype._onPointerMove = function (e) {
  37027. // If the current pointer is the one associated to the joystick (first touch contact)
  37028. if (this._joystickPointerID == e.pointerId) {
  37029. this._joystickPointerPos.x = e.clientX;
  37030. this._joystickPointerPos.y = e.clientY;
  37031. this._deltaJoystickVector = this._joystickPointerPos.clone();
  37032. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  37033. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  37034. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  37035. switch (this._axisTargetedByLeftAndRight) {
  37036. case JoystickAxis.X:
  37037. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  37038. break;
  37039. case JoystickAxis.Y:
  37040. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  37041. break;
  37042. case JoystickAxis.Z:
  37043. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  37044. break;
  37045. }
  37046. var directionUpDown = this.reverseUpDown ? 1 : -1;
  37047. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  37048. switch (this._axisTargetedByUpAndDown) {
  37049. case JoystickAxis.X:
  37050. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  37051. break;
  37052. case JoystickAxis.Y:
  37053. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  37054. break;
  37055. case JoystickAxis.Z:
  37056. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  37057. break;
  37058. }
  37059. }
  37060. else {
  37061. if (this._touches.item(e.pointerId.toString())) {
  37062. this._touches.item(e.pointerId.toString()).x = e.clientX;
  37063. this._touches.item(e.pointerId.toString()).y = e.clientY;
  37064. }
  37065. }
  37066. };
  37067. VirtualJoystick.prototype._onPointerUp = function (e) {
  37068. if (this._joystickPointerID == e.pointerId) {
  37069. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  37070. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  37071. this._joystickPointerID = -1;
  37072. this.pressed = false;
  37073. }
  37074. else {
  37075. var touch = this._touches.item(e.pointerId.toString());
  37076. if (touch) {
  37077. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37078. }
  37079. }
  37080. this._deltaJoystickVector.x = 0;
  37081. this._deltaJoystickVector.y = 0;
  37082. this._touches.remove(e.pointerId.toString());
  37083. };
  37084. /**
  37085. * Change the color of the virtual joystick
  37086. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  37087. */
  37088. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  37089. this._joystickColor = newColor;
  37090. };
  37091. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  37092. this._action = action;
  37093. };
  37094. // Define which axis you'd like to control for left & right
  37095. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  37096. switch (axis) {
  37097. case JoystickAxis.X:
  37098. case JoystickAxis.Y:
  37099. case JoystickAxis.Z:
  37100. this._axisTargetedByLeftAndRight = axis;
  37101. break;
  37102. default:
  37103. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  37104. break;
  37105. }
  37106. };
  37107. // Define which axis you'd like to control for up & down
  37108. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  37109. switch (axis) {
  37110. case JoystickAxis.X:
  37111. case JoystickAxis.Y:
  37112. case JoystickAxis.Z:
  37113. this._axisTargetedByUpAndDown = axis;
  37114. break;
  37115. default:
  37116. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  37117. break;
  37118. }
  37119. };
  37120. VirtualJoystick.prototype._clearCanvas = function () {
  37121. if (this._leftJoystick) {
  37122. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  37123. }
  37124. else {
  37125. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  37126. }
  37127. };
  37128. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  37129. var _this = this;
  37130. if (this.pressed) {
  37131. this._touches.forEach(function (touch) {
  37132. if (touch.pointerId === _this._joystickPointerID) {
  37133. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  37134. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  37135. VirtualJoystick.vjCanvasContext.beginPath();
  37136. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37137. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37138. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  37139. VirtualJoystick.vjCanvasContext.stroke();
  37140. VirtualJoystick.vjCanvasContext.closePath();
  37141. VirtualJoystick.vjCanvasContext.beginPath();
  37142. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37143. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  37144. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  37145. VirtualJoystick.vjCanvasContext.stroke();
  37146. VirtualJoystick.vjCanvasContext.closePath();
  37147. VirtualJoystick.vjCanvasContext.beginPath();
  37148. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37149. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  37150. VirtualJoystick.vjCanvasContext.stroke();
  37151. VirtualJoystick.vjCanvasContext.closePath();
  37152. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  37153. }
  37154. else {
  37155. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37156. VirtualJoystick.vjCanvasContext.beginPath();
  37157. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  37158. VirtualJoystick.vjCanvasContext.beginPath();
  37159. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  37160. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37161. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  37162. VirtualJoystick.vjCanvasContext.stroke();
  37163. VirtualJoystick.vjCanvasContext.closePath();
  37164. touch.prevX = touch.x;
  37165. touch.prevY = touch.y;
  37166. }
  37167. ;
  37168. });
  37169. }
  37170. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  37171. };
  37172. VirtualJoystick.prototype.releaseCanvas = function () {
  37173. if (VirtualJoystick.vjCanvas) {
  37174. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  37175. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  37176. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  37177. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  37178. window.removeEventListener("resize", this._onResize);
  37179. document.body.removeChild(VirtualJoystick.vjCanvas);
  37180. VirtualJoystick.vjCanvas = null;
  37181. }
  37182. };
  37183. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  37184. VirtualJoystick._globalJoystickIndex = 0;
  37185. return VirtualJoystick;
  37186. })();
  37187. BABYLON.VirtualJoystick = VirtualJoystick;
  37188. })(BABYLON || (BABYLON = {}));
  37189. var BABYLON;
  37190. (function (BABYLON) {
  37191. // We're mainly based on the logic defined into the FreeCamera code
  37192. var VirtualJoysticksCamera = (function (_super) {
  37193. __extends(VirtualJoysticksCamera, _super);
  37194. function VirtualJoysticksCamera(name, position, scene) {
  37195. _super.call(this, name, position, scene);
  37196. this.inputs.addVirtualJoystick();
  37197. }
  37198. return VirtualJoysticksCamera;
  37199. })(BABYLON.FreeCamera);
  37200. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  37201. })(BABYLON || (BABYLON = {}));
  37202. var BABYLON;
  37203. (function (BABYLON) {
  37204. var AnaglyphPostProcess = (function (_super) {
  37205. __extends(AnaglyphPostProcess, _super);
  37206. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37207. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  37208. }
  37209. return AnaglyphPostProcess;
  37210. })(BABYLON.PostProcess);
  37211. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  37212. })(BABYLON || (BABYLON = {}));
  37213. var BABYLON;
  37214. (function (BABYLON) {
  37215. var OutlineRenderer = (function () {
  37216. function OutlineRenderer(scene) {
  37217. this._scene = scene;
  37218. }
  37219. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  37220. var _this = this;
  37221. if (useOverlay === void 0) { useOverlay = false; }
  37222. var scene = this._scene;
  37223. var engine = this._scene.getEngine();
  37224. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37225. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  37226. return;
  37227. }
  37228. var mesh = subMesh.getRenderingMesh();
  37229. var material = subMesh.getMaterial();
  37230. engine.enableEffect(this._effect);
  37231. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  37232. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  37233. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  37234. // Bones
  37235. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37236. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37237. }
  37238. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  37239. // Alpha test
  37240. if (material && material.needAlphaTesting()) {
  37241. var alphaTexture = material.getAlphaTestTexture();
  37242. this._effect.setTexture("diffuseSampler", alphaTexture);
  37243. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37244. }
  37245. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  37246. };
  37247. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  37248. var defines = [];
  37249. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  37250. var mesh = subMesh.getMesh();
  37251. var material = subMesh.getMaterial();
  37252. // Alpha test
  37253. if (material && material.needAlphaTesting()) {
  37254. defines.push("#define ALPHATEST");
  37255. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37256. attribs.push(BABYLON.VertexBuffer.UVKind);
  37257. defines.push("#define UV1");
  37258. }
  37259. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37260. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37261. defines.push("#define UV2");
  37262. }
  37263. }
  37264. // Bones
  37265. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37266. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37267. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37268. if (mesh.numBoneInfluencers > 4) {
  37269. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37270. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37271. }
  37272. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37273. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37274. }
  37275. else {
  37276. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37277. }
  37278. // Instances
  37279. if (useInstances) {
  37280. defines.push("#define INSTANCES");
  37281. attribs.push("world0");
  37282. attribs.push("world1");
  37283. attribs.push("world2");
  37284. attribs.push("world3");
  37285. }
  37286. // Get correct effect
  37287. var join = defines.join("\n");
  37288. if (this._cachedDefines !== join) {
  37289. this._cachedDefines = join;
  37290. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  37291. }
  37292. return this._effect.isReady();
  37293. };
  37294. return OutlineRenderer;
  37295. })();
  37296. BABYLON.OutlineRenderer = OutlineRenderer;
  37297. })(BABYLON || (BABYLON = {}));
  37298. var BABYLON;
  37299. (function (BABYLON) {
  37300. var MeshAssetTask = (function () {
  37301. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  37302. this.name = name;
  37303. this.meshesNames = meshesNames;
  37304. this.rootUrl = rootUrl;
  37305. this.sceneFilename = sceneFilename;
  37306. this.isCompleted = false;
  37307. }
  37308. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37309. var _this = this;
  37310. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  37311. _this.loadedMeshes = meshes;
  37312. _this.loadedParticleSystems = particleSystems;
  37313. _this.loadedSkeletons = skeletons;
  37314. _this.isCompleted = true;
  37315. if (_this.onSuccess) {
  37316. _this.onSuccess(_this);
  37317. }
  37318. onSuccess();
  37319. }, null, function () {
  37320. if (_this.onError) {
  37321. _this.onError(_this);
  37322. }
  37323. onError();
  37324. });
  37325. };
  37326. return MeshAssetTask;
  37327. })();
  37328. BABYLON.MeshAssetTask = MeshAssetTask;
  37329. var TextFileAssetTask = (function () {
  37330. function TextFileAssetTask(name, url) {
  37331. this.name = name;
  37332. this.url = url;
  37333. this.isCompleted = false;
  37334. }
  37335. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37336. var _this = this;
  37337. BABYLON.Tools.LoadFile(this.url, function (data) {
  37338. _this.text = data;
  37339. _this.isCompleted = true;
  37340. if (_this.onSuccess) {
  37341. _this.onSuccess(_this);
  37342. }
  37343. onSuccess();
  37344. }, null, scene.database, false, function () {
  37345. if (_this.onError) {
  37346. _this.onError(_this);
  37347. }
  37348. onError();
  37349. });
  37350. };
  37351. return TextFileAssetTask;
  37352. })();
  37353. BABYLON.TextFileAssetTask = TextFileAssetTask;
  37354. var BinaryFileAssetTask = (function () {
  37355. function BinaryFileAssetTask(name, url) {
  37356. this.name = name;
  37357. this.url = url;
  37358. this.isCompleted = false;
  37359. }
  37360. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37361. var _this = this;
  37362. BABYLON.Tools.LoadFile(this.url, function (data) {
  37363. _this.data = data;
  37364. _this.isCompleted = true;
  37365. if (_this.onSuccess) {
  37366. _this.onSuccess(_this);
  37367. }
  37368. onSuccess();
  37369. }, null, scene.database, true, function () {
  37370. if (_this.onError) {
  37371. _this.onError(_this);
  37372. }
  37373. onError();
  37374. });
  37375. };
  37376. return BinaryFileAssetTask;
  37377. })();
  37378. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  37379. var ImageAssetTask = (function () {
  37380. function ImageAssetTask(name, url) {
  37381. this.name = name;
  37382. this.url = url;
  37383. this.isCompleted = false;
  37384. }
  37385. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37386. var _this = this;
  37387. var img = new Image();
  37388. img.onload = function () {
  37389. _this.image = img;
  37390. _this.isCompleted = true;
  37391. if (_this.onSuccess) {
  37392. _this.onSuccess(_this);
  37393. }
  37394. onSuccess();
  37395. };
  37396. img.onerror = function () {
  37397. if (_this.onError) {
  37398. _this.onError(_this);
  37399. }
  37400. onError();
  37401. };
  37402. img.src = this.url;
  37403. };
  37404. return ImageAssetTask;
  37405. })();
  37406. BABYLON.ImageAssetTask = ImageAssetTask;
  37407. var TextureAssetTask = (function () {
  37408. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  37409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37410. this.name = name;
  37411. this.url = url;
  37412. this.noMipmap = noMipmap;
  37413. this.invertY = invertY;
  37414. this.samplingMode = samplingMode;
  37415. this.isCompleted = false;
  37416. }
  37417. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37418. var _this = this;
  37419. var onload = function () {
  37420. _this.isCompleted = true;
  37421. if (_this.onSuccess) {
  37422. _this.onSuccess(_this);
  37423. }
  37424. onSuccess();
  37425. };
  37426. var onerror = function () {
  37427. if (_this.onError) {
  37428. _this.onError(_this);
  37429. }
  37430. onError();
  37431. };
  37432. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  37433. };
  37434. return TextureAssetTask;
  37435. })();
  37436. BABYLON.TextureAssetTask = TextureAssetTask;
  37437. var AssetsManager = (function () {
  37438. function AssetsManager(scene) {
  37439. this._tasks = new Array();
  37440. this._waitingTasksCount = 0;
  37441. this.useDefaultLoadingScreen = true;
  37442. this._scene = scene;
  37443. }
  37444. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  37445. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  37446. this._tasks.push(task);
  37447. return task;
  37448. };
  37449. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  37450. var task = new TextFileAssetTask(taskName, url);
  37451. this._tasks.push(task);
  37452. return task;
  37453. };
  37454. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  37455. var task = new BinaryFileAssetTask(taskName, url);
  37456. this._tasks.push(task);
  37457. return task;
  37458. };
  37459. AssetsManager.prototype.addImageTask = function (taskName, url) {
  37460. var task = new ImageAssetTask(taskName, url);
  37461. this._tasks.push(task);
  37462. return task;
  37463. };
  37464. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  37465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37466. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  37467. this._tasks.push(task);
  37468. return task;
  37469. };
  37470. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  37471. this._waitingTasksCount--;
  37472. if (this._waitingTasksCount === 0) {
  37473. if (this.onFinish) {
  37474. this.onFinish(this._tasks);
  37475. }
  37476. this._scene.getEngine().hideLoadingUI();
  37477. }
  37478. };
  37479. AssetsManager.prototype._runTask = function (task) {
  37480. var _this = this;
  37481. task.run(this._scene, function () {
  37482. if (_this.onTaskSuccess) {
  37483. _this.onTaskSuccess(task);
  37484. }
  37485. _this._decreaseWaitingTasksCount();
  37486. }, function () {
  37487. if (_this.onTaskError) {
  37488. _this.onTaskError(task);
  37489. }
  37490. _this._decreaseWaitingTasksCount();
  37491. });
  37492. };
  37493. AssetsManager.prototype.reset = function () {
  37494. this._tasks = new Array();
  37495. return this;
  37496. };
  37497. AssetsManager.prototype.load = function () {
  37498. this._waitingTasksCount = this._tasks.length;
  37499. if (this._waitingTasksCount === 0) {
  37500. if (this.onFinish) {
  37501. this.onFinish(this._tasks);
  37502. }
  37503. return this;
  37504. }
  37505. if (this.useDefaultLoadingScreen) {
  37506. this._scene.getEngine().displayLoadingUI();
  37507. }
  37508. for (var index = 0; index < this._tasks.length; index++) {
  37509. var task = this._tasks[index];
  37510. this._runTask(task);
  37511. }
  37512. return this;
  37513. };
  37514. return AssetsManager;
  37515. })();
  37516. BABYLON.AssetsManager = AssetsManager;
  37517. })(BABYLON || (BABYLON = {}));
  37518. var BABYLON;
  37519. (function (BABYLON) {
  37520. var VRCameraMetrics = (function () {
  37521. function VRCameraMetrics() {
  37522. this.compensateDistortion = true;
  37523. }
  37524. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  37525. get: function () {
  37526. return this.hResolution / (2 * this.vResolution);
  37527. },
  37528. enumerable: true,
  37529. configurable: true
  37530. });
  37531. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  37532. get: function () {
  37533. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  37534. },
  37535. enumerable: true,
  37536. configurable: true
  37537. });
  37538. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  37539. get: function () {
  37540. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37541. var h = (4 * meters) / this.hScreenSize;
  37542. return BABYLON.Matrix.Translation(h, 0, 0);
  37543. },
  37544. enumerable: true,
  37545. configurable: true
  37546. });
  37547. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  37548. get: function () {
  37549. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37550. var h = (4 * meters) / this.hScreenSize;
  37551. return BABYLON.Matrix.Translation(-h, 0, 0);
  37552. },
  37553. enumerable: true,
  37554. configurable: true
  37555. });
  37556. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  37557. get: function () {
  37558. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  37559. },
  37560. enumerable: true,
  37561. configurable: true
  37562. });
  37563. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  37564. get: function () {
  37565. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  37566. },
  37567. enumerable: true,
  37568. configurable: true
  37569. });
  37570. VRCameraMetrics.GetDefault = function () {
  37571. var result = new VRCameraMetrics();
  37572. result.hResolution = 1280;
  37573. result.vResolution = 800;
  37574. result.hScreenSize = 0.149759993;
  37575. result.vScreenSize = 0.0935999975;
  37576. result.vScreenCenter = 0.0467999987,
  37577. result.eyeToScreenDistance = 0.0410000011;
  37578. result.lensSeparationDistance = 0.0635000020;
  37579. result.interpupillaryDistance = 0.0640000030;
  37580. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  37581. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  37582. result.postProcessScaleFactor = 1.714605507808412;
  37583. result.lensCenterOffset = 0.151976421;
  37584. return result;
  37585. };
  37586. return VRCameraMetrics;
  37587. })();
  37588. BABYLON.VRCameraMetrics = VRCameraMetrics;
  37589. })(BABYLON || (BABYLON = {}));
  37590. var BABYLON;
  37591. (function (BABYLON) {
  37592. var VRDeviceOrientationFreeCamera = (function (_super) {
  37593. __extends(VRDeviceOrientationFreeCamera, _super);
  37594. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  37595. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37596. _super.call(this, name, position, scene);
  37597. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37598. metrics.compensateDistortion = compensateDistortion;
  37599. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37600. this.inputs.addVRDeviceOrientation();
  37601. }
  37602. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  37603. return "VRDeviceOrientationFreeCamera";
  37604. };
  37605. return VRDeviceOrientationFreeCamera;
  37606. })(BABYLON.FreeCamera);
  37607. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  37608. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  37609. __extends(VRDeviceOrientationArcRotateCamera, _super);
  37610. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  37611. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37612. _super.call(this, name, alpha, beta, radius, target, scene);
  37613. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37614. metrics.compensateDistortion = compensateDistortion;
  37615. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37616. this.inputs.addVRDeviceOrientation();
  37617. }
  37618. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  37619. return "VRDeviceOrientationArcRotateCamera";
  37620. };
  37621. return VRDeviceOrientationArcRotateCamera;
  37622. })(BABYLON.ArcRotateCamera);
  37623. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  37624. })(BABYLON || (BABYLON = {}));
  37625. var BABYLON;
  37626. (function (BABYLON) {
  37627. var WebVRFreeCamera = (function (_super) {
  37628. __extends(WebVRFreeCamera, _super);
  37629. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  37630. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37631. _super.call(this, name, position, scene);
  37632. this._hmdDevice = null;
  37633. this._sensorDevice = null;
  37634. this._cacheState = null;
  37635. this._cacheQuaternion = new BABYLON.Quaternion();
  37636. this._cacheRotation = BABYLON.Vector3.Zero();
  37637. this._vrEnabled = false;
  37638. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37639. metrics.compensateDistortion = compensateDistortion;
  37640. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37641. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  37642. }
  37643. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  37644. var size = devices.length;
  37645. var i = 0;
  37646. // Reset devices.
  37647. this._sensorDevice = null;
  37648. this._hmdDevice = null;
  37649. // Search for a HmdDevice.
  37650. while (i < size && this._hmdDevice === null) {
  37651. if (devices[i] instanceof HMDVRDevice) {
  37652. this._hmdDevice = devices[i];
  37653. }
  37654. i++;
  37655. }
  37656. i = 0;
  37657. while (i < size && this._sensorDevice === null) {
  37658. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  37659. this._sensorDevice = devices[i];
  37660. }
  37661. i++;
  37662. }
  37663. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  37664. };
  37665. WebVRFreeCamera.prototype._checkInputs = function () {
  37666. if (this._vrEnabled) {
  37667. this._cacheState = this._sensorDevice.getState();
  37668. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  37669. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  37670. this.rotation.x = -this._cacheRotation.x;
  37671. this.rotation.y = -this._cacheRotation.y;
  37672. this.rotation.z = this._cacheRotation.z;
  37673. }
  37674. _super.prototype._checkInputs.call(this);
  37675. };
  37676. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37677. _super.prototype.attachControl.call(this, element, noPreventDefault);
  37678. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37679. if (navigator.getVRDevices) {
  37680. navigator.getVRDevices().then(this._getWebVRDevices);
  37681. }
  37682. else if (navigator.mozGetVRDevices) {
  37683. navigator.mozGetVRDevices(this._getWebVRDevices);
  37684. }
  37685. };
  37686. WebVRFreeCamera.prototype.detachControl = function (element) {
  37687. _super.prototype.detachControl.call(this, element);
  37688. this._vrEnabled = false;
  37689. };
  37690. WebVRFreeCamera.prototype.getTypeName = function () {
  37691. return "WebVRFreeCamera";
  37692. };
  37693. return WebVRFreeCamera;
  37694. })(BABYLON.FreeCamera);
  37695. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  37696. })(BABYLON || (BABYLON = {}));
  37697. var BABYLON;
  37698. (function (BABYLON) {
  37699. // Standard optimizations
  37700. var SceneOptimization = (function () {
  37701. function SceneOptimization(priority) {
  37702. if (priority === void 0) { priority = 0; }
  37703. this.priority = priority;
  37704. this.apply = function (scene) {
  37705. return true; // Return true if everything that can be done was applied
  37706. };
  37707. }
  37708. return SceneOptimization;
  37709. })();
  37710. BABYLON.SceneOptimization = SceneOptimization;
  37711. var TextureOptimization = (function (_super) {
  37712. __extends(TextureOptimization, _super);
  37713. function TextureOptimization(priority, maximumSize) {
  37714. var _this = this;
  37715. if (priority === void 0) { priority = 0; }
  37716. if (maximumSize === void 0) { maximumSize = 1024; }
  37717. _super.call(this, priority);
  37718. this.priority = priority;
  37719. this.maximumSize = maximumSize;
  37720. this.apply = function (scene) {
  37721. var allDone = true;
  37722. for (var index = 0; index < scene.textures.length; index++) {
  37723. var texture = scene.textures[index];
  37724. if (!texture.canRescale) {
  37725. continue;
  37726. }
  37727. var currentSize = texture.getSize();
  37728. var maxDimension = Math.max(currentSize.width, currentSize.height);
  37729. if (maxDimension > _this.maximumSize) {
  37730. texture.scale(0.5);
  37731. allDone = false;
  37732. }
  37733. }
  37734. return allDone;
  37735. };
  37736. }
  37737. return TextureOptimization;
  37738. })(SceneOptimization);
  37739. BABYLON.TextureOptimization = TextureOptimization;
  37740. var HardwareScalingOptimization = (function (_super) {
  37741. __extends(HardwareScalingOptimization, _super);
  37742. function HardwareScalingOptimization(priority, maximumScale) {
  37743. var _this = this;
  37744. if (priority === void 0) { priority = 0; }
  37745. if (maximumScale === void 0) { maximumScale = 2; }
  37746. _super.call(this, priority);
  37747. this.priority = priority;
  37748. this.maximumScale = maximumScale;
  37749. this._currentScale = 1;
  37750. this.apply = function (scene) {
  37751. _this._currentScale++;
  37752. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  37753. return _this._currentScale >= _this.maximumScale;
  37754. };
  37755. }
  37756. return HardwareScalingOptimization;
  37757. })(SceneOptimization);
  37758. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  37759. var ShadowsOptimization = (function (_super) {
  37760. __extends(ShadowsOptimization, _super);
  37761. function ShadowsOptimization() {
  37762. _super.apply(this, arguments);
  37763. this.apply = function (scene) {
  37764. scene.shadowsEnabled = false;
  37765. return true;
  37766. };
  37767. }
  37768. return ShadowsOptimization;
  37769. })(SceneOptimization);
  37770. BABYLON.ShadowsOptimization = ShadowsOptimization;
  37771. var PostProcessesOptimization = (function (_super) {
  37772. __extends(PostProcessesOptimization, _super);
  37773. function PostProcessesOptimization() {
  37774. _super.apply(this, arguments);
  37775. this.apply = function (scene) {
  37776. scene.postProcessesEnabled = false;
  37777. return true;
  37778. };
  37779. }
  37780. return PostProcessesOptimization;
  37781. })(SceneOptimization);
  37782. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  37783. var LensFlaresOptimization = (function (_super) {
  37784. __extends(LensFlaresOptimization, _super);
  37785. function LensFlaresOptimization() {
  37786. _super.apply(this, arguments);
  37787. this.apply = function (scene) {
  37788. scene.lensFlaresEnabled = false;
  37789. return true;
  37790. };
  37791. }
  37792. return LensFlaresOptimization;
  37793. })(SceneOptimization);
  37794. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  37795. var ParticlesOptimization = (function (_super) {
  37796. __extends(ParticlesOptimization, _super);
  37797. function ParticlesOptimization() {
  37798. _super.apply(this, arguments);
  37799. this.apply = function (scene) {
  37800. scene.particlesEnabled = false;
  37801. return true;
  37802. };
  37803. }
  37804. return ParticlesOptimization;
  37805. })(SceneOptimization);
  37806. BABYLON.ParticlesOptimization = ParticlesOptimization;
  37807. var RenderTargetsOptimization = (function (_super) {
  37808. __extends(RenderTargetsOptimization, _super);
  37809. function RenderTargetsOptimization() {
  37810. _super.apply(this, arguments);
  37811. this.apply = function (scene) {
  37812. scene.renderTargetsEnabled = false;
  37813. return true;
  37814. };
  37815. }
  37816. return RenderTargetsOptimization;
  37817. })(SceneOptimization);
  37818. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  37819. var MergeMeshesOptimization = (function (_super) {
  37820. __extends(MergeMeshesOptimization, _super);
  37821. function MergeMeshesOptimization() {
  37822. var _this = this;
  37823. _super.apply(this, arguments);
  37824. this._canBeMerged = function (abstractMesh) {
  37825. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  37826. return false;
  37827. }
  37828. var mesh = abstractMesh;
  37829. if (!mesh.isVisible || !mesh.isEnabled()) {
  37830. return false;
  37831. }
  37832. if (mesh.instances.length > 0) {
  37833. return false;
  37834. }
  37835. if (mesh.skeleton || mesh.hasLODLevels) {
  37836. return false;
  37837. }
  37838. if (mesh.parent) {
  37839. return false;
  37840. }
  37841. return true;
  37842. };
  37843. this.apply = function (scene, updateSelectionTree) {
  37844. var globalPool = scene.meshes.slice(0);
  37845. var globalLength = globalPool.length;
  37846. for (var index = 0; index < globalLength; index++) {
  37847. var currentPool = new Array();
  37848. var current = globalPool[index];
  37849. // Checks
  37850. if (!_this._canBeMerged(current)) {
  37851. continue;
  37852. }
  37853. currentPool.push(current);
  37854. // Find compatible meshes
  37855. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  37856. var otherMesh = globalPool[subIndex];
  37857. if (!_this._canBeMerged(otherMesh)) {
  37858. continue;
  37859. }
  37860. if (otherMesh.material !== current.material) {
  37861. continue;
  37862. }
  37863. if (otherMesh.checkCollisions !== current.checkCollisions) {
  37864. continue;
  37865. }
  37866. currentPool.push(otherMesh);
  37867. globalLength--;
  37868. globalPool.splice(subIndex, 1);
  37869. subIndex--;
  37870. }
  37871. if (currentPool.length < 2) {
  37872. continue;
  37873. }
  37874. // Merge meshes
  37875. BABYLON.Mesh.MergeMeshes(currentPool);
  37876. }
  37877. if (updateSelectionTree != undefined) {
  37878. if (updateSelectionTree) {
  37879. scene.createOrUpdateSelectionOctree();
  37880. }
  37881. }
  37882. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  37883. scene.createOrUpdateSelectionOctree();
  37884. }
  37885. return true;
  37886. };
  37887. }
  37888. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  37889. get: function () {
  37890. return MergeMeshesOptimization._UpdateSelectionTree;
  37891. },
  37892. set: function (value) {
  37893. MergeMeshesOptimization._UpdateSelectionTree = value;
  37894. },
  37895. enumerable: true,
  37896. configurable: true
  37897. });
  37898. MergeMeshesOptimization._UpdateSelectionTree = false;
  37899. return MergeMeshesOptimization;
  37900. })(SceneOptimization);
  37901. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  37902. // Options
  37903. var SceneOptimizerOptions = (function () {
  37904. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  37905. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  37906. if (trackerDuration === void 0) { trackerDuration = 2000; }
  37907. this.targetFrameRate = targetFrameRate;
  37908. this.trackerDuration = trackerDuration;
  37909. this.optimizations = new Array();
  37910. }
  37911. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  37912. var result = new SceneOptimizerOptions(targetFrameRate);
  37913. var priority = 0;
  37914. result.optimizations.push(new MergeMeshesOptimization(priority));
  37915. result.optimizations.push(new ShadowsOptimization(priority));
  37916. result.optimizations.push(new LensFlaresOptimization(priority));
  37917. // Next priority
  37918. priority++;
  37919. result.optimizations.push(new PostProcessesOptimization(priority));
  37920. result.optimizations.push(new ParticlesOptimization(priority));
  37921. // Next priority
  37922. priority++;
  37923. result.optimizations.push(new TextureOptimization(priority, 1024));
  37924. return result;
  37925. };
  37926. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  37927. var result = new SceneOptimizerOptions(targetFrameRate);
  37928. var priority = 0;
  37929. result.optimizations.push(new MergeMeshesOptimization(priority));
  37930. result.optimizations.push(new ShadowsOptimization(priority));
  37931. result.optimizations.push(new LensFlaresOptimization(priority));
  37932. // Next priority
  37933. priority++;
  37934. result.optimizations.push(new PostProcessesOptimization(priority));
  37935. result.optimizations.push(new ParticlesOptimization(priority));
  37936. // Next priority
  37937. priority++;
  37938. result.optimizations.push(new TextureOptimization(priority, 512));
  37939. // Next priority
  37940. priority++;
  37941. result.optimizations.push(new RenderTargetsOptimization(priority));
  37942. // Next priority
  37943. priority++;
  37944. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  37945. return result;
  37946. };
  37947. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  37948. var result = new SceneOptimizerOptions(targetFrameRate);
  37949. var priority = 0;
  37950. result.optimizations.push(new MergeMeshesOptimization(priority));
  37951. result.optimizations.push(new ShadowsOptimization(priority));
  37952. result.optimizations.push(new LensFlaresOptimization(priority));
  37953. // Next priority
  37954. priority++;
  37955. result.optimizations.push(new PostProcessesOptimization(priority));
  37956. result.optimizations.push(new ParticlesOptimization(priority));
  37957. // Next priority
  37958. priority++;
  37959. result.optimizations.push(new TextureOptimization(priority, 256));
  37960. // Next priority
  37961. priority++;
  37962. result.optimizations.push(new RenderTargetsOptimization(priority));
  37963. // Next priority
  37964. priority++;
  37965. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  37966. return result;
  37967. };
  37968. return SceneOptimizerOptions;
  37969. })();
  37970. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  37971. // Scene optimizer tool
  37972. var SceneOptimizer = (function () {
  37973. function SceneOptimizer() {
  37974. }
  37975. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  37976. // TODO: add an epsilon
  37977. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  37978. if (onSuccess) {
  37979. onSuccess();
  37980. }
  37981. return;
  37982. }
  37983. // Apply current level of optimizations
  37984. var allDone = true;
  37985. var noOptimizationApplied = true;
  37986. for (var index = 0; index < options.optimizations.length; index++) {
  37987. var optimization = options.optimizations[index];
  37988. if (optimization.priority === currentPriorityLevel) {
  37989. noOptimizationApplied = false;
  37990. allDone = allDone && optimization.apply(scene);
  37991. }
  37992. }
  37993. // If no optimization was applied, this is a failure :(
  37994. if (noOptimizationApplied) {
  37995. if (onFailure) {
  37996. onFailure();
  37997. }
  37998. return;
  37999. }
  38000. // If all optimizations were done, move to next level
  38001. if (allDone) {
  38002. currentPriorityLevel++;
  38003. }
  38004. // Let's the system running for a specific amount of time before checking FPS
  38005. scene.executeWhenReady(function () {
  38006. setTimeout(function () {
  38007. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  38008. }, options.trackerDuration);
  38009. });
  38010. };
  38011. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  38012. if (!options) {
  38013. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  38014. }
  38015. // Let's the system running for a specific amount of time before checking FPS
  38016. scene.executeWhenReady(function () {
  38017. setTimeout(function () {
  38018. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  38019. }, options.trackerDuration);
  38020. });
  38021. };
  38022. return SceneOptimizer;
  38023. })();
  38024. BABYLON.SceneOptimizer = SceneOptimizer;
  38025. })(BABYLON || (BABYLON = {}));
  38026. var BABYLON;
  38027. (function (BABYLON) {
  38028. var Internals;
  38029. (function (Internals) {
  38030. var MeshLODLevel = (function () {
  38031. function MeshLODLevel(distance, mesh) {
  38032. this.distance = distance;
  38033. this.mesh = mesh;
  38034. }
  38035. return MeshLODLevel;
  38036. })();
  38037. Internals.MeshLODLevel = MeshLODLevel;
  38038. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38039. })(BABYLON || (BABYLON = {}));
  38040. var BABYLON;
  38041. (function (BABYLON) {
  38042. var RawTexture = (function (_super) {
  38043. __extends(RawTexture, _super);
  38044. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  38045. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38046. if (invertY === void 0) { invertY = false; }
  38047. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38048. _super.call(this, null, scene, !generateMipMaps, invertY);
  38049. this.format = format;
  38050. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  38051. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38052. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38053. }
  38054. RawTexture.prototype.update = function (data) {
  38055. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  38056. };
  38057. // Statics
  38058. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38059. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38060. if (invertY === void 0) { invertY = false; }
  38061. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38062. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  38063. };
  38064. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38065. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38066. if (invertY === void 0) { invertY = false; }
  38067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38068. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38069. };
  38070. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38071. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38072. if (invertY === void 0) { invertY = false; }
  38073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38074. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38075. };
  38076. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38077. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38078. if (invertY === void 0) { invertY = false; }
  38079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38080. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  38081. };
  38082. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38083. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38084. if (invertY === void 0) { invertY = false; }
  38085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38086. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  38087. };
  38088. return RawTexture;
  38089. })(BABYLON.Texture);
  38090. BABYLON.RawTexture = RawTexture;
  38091. })(BABYLON || (BABYLON = {}));
  38092. var BABYLON;
  38093. (function (BABYLON) {
  38094. var IndexedVector2 = (function (_super) {
  38095. __extends(IndexedVector2, _super);
  38096. function IndexedVector2(original, index) {
  38097. _super.call(this, original.x, original.y);
  38098. this.index = index;
  38099. }
  38100. return IndexedVector2;
  38101. })(BABYLON.Vector2);
  38102. var PolygonPoints = (function () {
  38103. function PolygonPoints() {
  38104. this.elements = new Array();
  38105. }
  38106. PolygonPoints.prototype.add = function (originalPoints) {
  38107. var _this = this;
  38108. var result = new Array();
  38109. originalPoints.forEach(function (point) {
  38110. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  38111. var newPoint = new IndexedVector2(point, _this.elements.length);
  38112. result.push(newPoint);
  38113. _this.elements.push(newPoint);
  38114. }
  38115. });
  38116. return result;
  38117. };
  38118. PolygonPoints.prototype.computeBounds = function () {
  38119. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38120. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38121. this.elements.forEach(function (point) {
  38122. // x
  38123. if (point.x < lmin.x) {
  38124. lmin.x = point.x;
  38125. }
  38126. else if (point.x > lmax.x) {
  38127. lmax.x = point.x;
  38128. }
  38129. // y
  38130. if (point.y < lmin.y) {
  38131. lmin.y = point.y;
  38132. }
  38133. else if (point.y > lmax.y) {
  38134. lmax.y = point.y;
  38135. }
  38136. });
  38137. return {
  38138. min: lmin,
  38139. max: lmax,
  38140. width: lmax.x - lmin.x,
  38141. height: lmax.y - lmin.y
  38142. };
  38143. };
  38144. return PolygonPoints;
  38145. })();
  38146. var Polygon = (function () {
  38147. function Polygon() {
  38148. }
  38149. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  38150. return [
  38151. new BABYLON.Vector2(xmin, ymin),
  38152. new BABYLON.Vector2(xmax, ymin),
  38153. new BABYLON.Vector2(xmax, ymax),
  38154. new BABYLON.Vector2(xmin, ymax)
  38155. ];
  38156. };
  38157. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  38158. if (cx === void 0) { cx = 0; }
  38159. if (cy === void 0) { cy = 0; }
  38160. if (numberOfSides === void 0) { numberOfSides = 32; }
  38161. var result = new Array();
  38162. var angle = 0;
  38163. var increment = (Math.PI * 2) / numberOfSides;
  38164. for (var i = 0; i < numberOfSides; i++) {
  38165. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  38166. angle -= increment;
  38167. }
  38168. return result;
  38169. };
  38170. Polygon.Parse = function (input) {
  38171. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  38172. var i, result = [];
  38173. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  38174. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  38175. }
  38176. return result;
  38177. };
  38178. Polygon.StartingAt = function (x, y) {
  38179. return BABYLON.Path2.StartingAt(x, y);
  38180. };
  38181. return Polygon;
  38182. })();
  38183. BABYLON.Polygon = Polygon;
  38184. var PolygonMeshBuilder = (function () {
  38185. function PolygonMeshBuilder(name, contours, scene) {
  38186. this._points = new PolygonPoints();
  38187. this._outlinepoints = new PolygonPoints();
  38188. this._holes = [];
  38189. if (!("poly2tri" in window)) {
  38190. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  38191. }
  38192. this._name = name;
  38193. this._scene = scene;
  38194. var points;
  38195. if (contours instanceof BABYLON.Path2) {
  38196. points = contours.getPoints();
  38197. }
  38198. else {
  38199. points = contours;
  38200. }
  38201. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  38202. this._outlinepoints.add(points);
  38203. }
  38204. PolygonMeshBuilder.prototype.addHole = function (hole) {
  38205. this._swctx.addHole(this._points.add(hole));
  38206. var holepoints = new PolygonPoints();
  38207. holepoints.add(hole);
  38208. this._holes.push(holepoints);
  38209. return this;
  38210. };
  38211. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  38212. var _this = this;
  38213. if (updatable === void 0) { updatable = false; }
  38214. var result = new BABYLON.Mesh(this._name, this._scene);
  38215. var normals = [];
  38216. var positions = [];
  38217. var uvs = [];
  38218. var bounds = this._points.computeBounds();
  38219. this._points.elements.forEach(function (p) {
  38220. normals.push(0, 1.0, 0);
  38221. positions.push(p.x, 0, p.y);
  38222. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  38223. });
  38224. var indices = [];
  38225. this._swctx.triangulate();
  38226. this._swctx.getTriangles().forEach(function (triangle) {
  38227. triangle.getPoints().forEach(function (point) {
  38228. indices.push(point.index);
  38229. });
  38230. });
  38231. if (depth > 0) {
  38232. var positionscount = (positions.length / 3); //get the current pointcount
  38233. this._points.elements.forEach(function (p) {
  38234. normals.push(0, -1.0, 0);
  38235. positions.push(p.x, -depth, p.y);
  38236. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  38237. });
  38238. var p1; //we need to change order of point so the triangles are made in the rigth way.
  38239. var p2;
  38240. var poscounter = 0;
  38241. this._swctx.getTriangles().forEach(function (triangle) {
  38242. triangle.getPoints().forEach(function (point) {
  38243. switch (poscounter) {
  38244. case 0:
  38245. p1 = point;
  38246. break;
  38247. case 1:
  38248. p2 = point;
  38249. break;
  38250. case 2:
  38251. indices.push(point.index + positionscount);
  38252. indices.push(p2.index + positionscount);
  38253. indices.push(p1.index + positionscount);
  38254. poscounter = -1;
  38255. break;
  38256. }
  38257. poscounter++;
  38258. //indices.push((<IndexedVector2>point).index + positionscount);
  38259. });
  38260. });
  38261. //Add the sides
  38262. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  38263. this._holes.forEach(function (hole) {
  38264. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  38265. });
  38266. }
  38267. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  38268. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  38269. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  38270. result.setIndices(indices);
  38271. return result;
  38272. };
  38273. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  38274. var StartIndex = positions.length / 3;
  38275. var ulength = 0;
  38276. for (var i = 0; i < points.elements.length; i++) {
  38277. var p = points.elements[i];
  38278. var p1;
  38279. if ((i + 1) > points.elements.length - 1) {
  38280. p1 = points.elements[0];
  38281. }
  38282. else {
  38283. p1 = points.elements[i + 1];
  38284. }
  38285. positions.push(p.x, 0, p.y);
  38286. positions.push(p.x, -depth, p.y);
  38287. positions.push(p1.x, 0, p1.y);
  38288. positions.push(p1.x, -depth, p1.y);
  38289. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  38290. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  38291. var v3 = v2.subtract(v1);
  38292. var v4 = new BABYLON.Vector3(0, 1, 0);
  38293. var vn = BABYLON.Vector3.Cross(v3, v4);
  38294. vn = vn.normalize();
  38295. uvs.push(ulength / bounds.width, 0);
  38296. uvs.push(ulength / bounds.width, 1);
  38297. ulength += v3.length();
  38298. uvs.push((ulength / bounds.width), 0);
  38299. uvs.push((ulength / bounds.width), 1);
  38300. if (!flip) {
  38301. normals.push(-vn.x, -vn.y, -vn.z);
  38302. normals.push(-vn.x, -vn.y, -vn.z);
  38303. normals.push(-vn.x, -vn.y, -vn.z);
  38304. normals.push(-vn.x, -vn.y, -vn.z);
  38305. indices.push(StartIndex);
  38306. indices.push(StartIndex + 1);
  38307. indices.push(StartIndex + 2);
  38308. indices.push(StartIndex + 1);
  38309. indices.push(StartIndex + 3);
  38310. indices.push(StartIndex + 2);
  38311. }
  38312. else {
  38313. normals.push(vn.x, vn.y, vn.z);
  38314. normals.push(vn.x, vn.y, vn.z);
  38315. normals.push(vn.x, vn.y, vn.z);
  38316. normals.push(vn.x, vn.y, vn.z);
  38317. indices.push(StartIndex);
  38318. indices.push(StartIndex + 2);
  38319. indices.push(StartIndex + 1);
  38320. indices.push(StartIndex + 1);
  38321. indices.push(StartIndex + 2);
  38322. indices.push(StartIndex + 3);
  38323. }
  38324. StartIndex += 4;
  38325. }
  38326. ;
  38327. };
  38328. return PolygonMeshBuilder;
  38329. })();
  38330. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  38331. })(BABYLON || (BABYLON = {}));
  38332. var BABYLON;
  38333. (function (BABYLON) {
  38334. var Octree = (function () {
  38335. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  38336. if (maxDepth === void 0) { maxDepth = 2; }
  38337. this.maxDepth = maxDepth;
  38338. this.dynamicContent = new Array();
  38339. this._maxBlockCapacity = maxBlockCapacity || 64;
  38340. this._selectionContent = new BABYLON.SmartArray(1024);
  38341. this._creationFunc = creationFunc;
  38342. }
  38343. // Methods
  38344. Octree.prototype.update = function (worldMin, worldMax, entries) {
  38345. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  38346. };
  38347. Octree.prototype.addMesh = function (entry) {
  38348. for (var index = 0; index < this.blocks.length; index++) {
  38349. var block = this.blocks[index];
  38350. block.addEntry(entry);
  38351. }
  38352. };
  38353. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  38354. this._selectionContent.reset();
  38355. for (var index = 0; index < this.blocks.length; index++) {
  38356. var block = this.blocks[index];
  38357. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  38358. }
  38359. if (allowDuplicate) {
  38360. this._selectionContent.concat(this.dynamicContent);
  38361. }
  38362. else {
  38363. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38364. }
  38365. return this._selectionContent;
  38366. };
  38367. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  38368. this._selectionContent.reset();
  38369. for (var index = 0; index < this.blocks.length; index++) {
  38370. var block = this.blocks[index];
  38371. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  38372. }
  38373. if (allowDuplicate) {
  38374. this._selectionContent.concat(this.dynamicContent);
  38375. }
  38376. else {
  38377. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38378. }
  38379. return this._selectionContent;
  38380. };
  38381. Octree.prototype.intersectsRay = function (ray) {
  38382. this._selectionContent.reset();
  38383. for (var index = 0; index < this.blocks.length; index++) {
  38384. var block = this.blocks[index];
  38385. block.intersectsRay(ray, this._selectionContent);
  38386. }
  38387. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38388. return this._selectionContent;
  38389. };
  38390. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  38391. target.blocks = new Array();
  38392. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  38393. // Segmenting space
  38394. for (var x = 0; x < 2; x++) {
  38395. for (var y = 0; y < 2; y++) {
  38396. for (var z = 0; z < 2; z++) {
  38397. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  38398. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  38399. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  38400. block.addEntries(entries);
  38401. target.blocks.push(block);
  38402. }
  38403. }
  38404. }
  38405. };
  38406. Octree.CreationFuncForMeshes = function (entry, block) {
  38407. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38408. block.entries.push(entry);
  38409. }
  38410. };
  38411. Octree.CreationFuncForSubMeshes = function (entry, block) {
  38412. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38413. block.entries.push(entry);
  38414. }
  38415. };
  38416. return Octree;
  38417. })();
  38418. BABYLON.Octree = Octree;
  38419. })(BABYLON || (BABYLON = {}));
  38420. var BABYLON;
  38421. (function (BABYLON) {
  38422. var OctreeBlock = (function () {
  38423. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  38424. this.entries = new Array();
  38425. this._boundingVectors = new Array();
  38426. this._capacity = capacity;
  38427. this._depth = depth;
  38428. this._maxDepth = maxDepth;
  38429. this._creationFunc = creationFunc;
  38430. this._minPoint = minPoint;
  38431. this._maxPoint = maxPoint;
  38432. this._boundingVectors.push(minPoint.clone());
  38433. this._boundingVectors.push(maxPoint.clone());
  38434. this._boundingVectors.push(minPoint.clone());
  38435. this._boundingVectors[2].x = maxPoint.x;
  38436. this._boundingVectors.push(minPoint.clone());
  38437. this._boundingVectors[3].y = maxPoint.y;
  38438. this._boundingVectors.push(minPoint.clone());
  38439. this._boundingVectors[4].z = maxPoint.z;
  38440. this._boundingVectors.push(maxPoint.clone());
  38441. this._boundingVectors[5].z = minPoint.z;
  38442. this._boundingVectors.push(maxPoint.clone());
  38443. this._boundingVectors[6].x = minPoint.x;
  38444. this._boundingVectors.push(maxPoint.clone());
  38445. this._boundingVectors[7].y = minPoint.y;
  38446. }
  38447. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  38448. // Property
  38449. get: function () {
  38450. return this._capacity;
  38451. },
  38452. enumerable: true,
  38453. configurable: true
  38454. });
  38455. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  38456. get: function () {
  38457. return this._minPoint;
  38458. },
  38459. enumerable: true,
  38460. configurable: true
  38461. });
  38462. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  38463. get: function () {
  38464. return this._maxPoint;
  38465. },
  38466. enumerable: true,
  38467. configurable: true
  38468. });
  38469. // Methods
  38470. OctreeBlock.prototype.addEntry = function (entry) {
  38471. if (this.blocks) {
  38472. for (var index = 0; index < this.blocks.length; index++) {
  38473. var block = this.blocks[index];
  38474. block.addEntry(entry);
  38475. }
  38476. return;
  38477. }
  38478. this._creationFunc(entry, this);
  38479. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  38480. this.createInnerBlocks();
  38481. }
  38482. };
  38483. OctreeBlock.prototype.addEntries = function (entries) {
  38484. for (var index = 0; index < entries.length; index++) {
  38485. var mesh = entries[index];
  38486. this.addEntry(mesh);
  38487. }
  38488. };
  38489. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  38490. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  38491. if (this.blocks) {
  38492. for (var index = 0; index < this.blocks.length; index++) {
  38493. var block = this.blocks[index];
  38494. block.select(frustumPlanes, selection, allowDuplicate);
  38495. }
  38496. return;
  38497. }
  38498. if (allowDuplicate) {
  38499. selection.concat(this.entries);
  38500. }
  38501. else {
  38502. selection.concatWithNoDuplicate(this.entries);
  38503. }
  38504. }
  38505. };
  38506. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  38507. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  38508. if (this.blocks) {
  38509. for (var index = 0; index < this.blocks.length; index++) {
  38510. var block = this.blocks[index];
  38511. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  38512. }
  38513. return;
  38514. }
  38515. if (allowDuplicate) {
  38516. selection.concat(this.entries);
  38517. }
  38518. else {
  38519. selection.concatWithNoDuplicate(this.entries);
  38520. }
  38521. }
  38522. };
  38523. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  38524. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  38525. if (this.blocks) {
  38526. for (var index = 0; index < this.blocks.length; index++) {
  38527. var block = this.blocks[index];
  38528. block.intersectsRay(ray, selection);
  38529. }
  38530. return;
  38531. }
  38532. selection.concatWithNoDuplicate(this.entries);
  38533. }
  38534. };
  38535. OctreeBlock.prototype.createInnerBlocks = function () {
  38536. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  38537. };
  38538. return OctreeBlock;
  38539. })();
  38540. BABYLON.OctreeBlock = OctreeBlock;
  38541. })(BABYLON || (BABYLON = {}));
  38542. var BABYLON;
  38543. (function (BABYLON) {
  38544. var BlurPostProcess = (function (_super) {
  38545. __extends(BlurPostProcess, _super);
  38546. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  38547. var _this = this;
  38548. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38549. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  38550. this.direction = direction;
  38551. this.blurWidth = blurWidth;
  38552. this.onApply = function (effect) {
  38553. effect.setFloat2("screenSize", _this.width, _this.height);
  38554. effect.setVector2("direction", _this.direction);
  38555. effect.setFloat("blurWidth", _this.blurWidth);
  38556. };
  38557. }
  38558. return BlurPostProcess;
  38559. })(BABYLON.PostProcess);
  38560. BABYLON.BlurPostProcess = BlurPostProcess;
  38561. })(BABYLON || (BABYLON = {}));
  38562. var BABYLON;
  38563. (function (BABYLON) {
  38564. var RefractionPostProcess = (function (_super) {
  38565. __extends(RefractionPostProcess, _super);
  38566. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  38567. var _this = this;
  38568. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  38569. this.color = color;
  38570. this.depth = depth;
  38571. this.colorLevel = colorLevel;
  38572. this.onActivate = function (cam) {
  38573. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  38574. };
  38575. this.onApply = function (effect) {
  38576. effect.setColor3("baseColor", _this.color);
  38577. effect.setFloat("depth", _this.depth);
  38578. effect.setFloat("colorLevel", _this.colorLevel);
  38579. effect.setTexture("refractionSampler", _this._refRexture);
  38580. };
  38581. }
  38582. // Methods
  38583. RefractionPostProcess.prototype.dispose = function (camera) {
  38584. if (this._refRexture) {
  38585. this._refRexture.dispose();
  38586. }
  38587. _super.prototype.dispose.call(this, camera);
  38588. };
  38589. return RefractionPostProcess;
  38590. })(BABYLON.PostProcess);
  38591. BABYLON.RefractionPostProcess = RefractionPostProcess;
  38592. })(BABYLON || (BABYLON = {}));
  38593. var BABYLON;
  38594. (function (BABYLON) {
  38595. var BlackAndWhitePostProcess = (function (_super) {
  38596. __extends(BlackAndWhitePostProcess, _super);
  38597. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38598. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  38599. }
  38600. return BlackAndWhitePostProcess;
  38601. })(BABYLON.PostProcess);
  38602. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  38603. })(BABYLON || (BABYLON = {}));
  38604. var BABYLON;
  38605. (function (BABYLON) {
  38606. var ConvolutionPostProcess = (function (_super) {
  38607. __extends(ConvolutionPostProcess, _super);
  38608. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  38609. var _this = this;
  38610. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  38611. this.kernel = kernel;
  38612. this.onApply = function (effect) {
  38613. effect.setFloat2("screenSize", _this.width, _this.height);
  38614. effect.setArray("kernel", _this.kernel);
  38615. };
  38616. }
  38617. // Statics
  38618. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  38619. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  38620. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  38621. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  38622. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  38623. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  38624. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  38625. return ConvolutionPostProcess;
  38626. })(BABYLON.PostProcess);
  38627. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  38628. })(BABYLON || (BABYLON = {}));
  38629. var BABYLON;
  38630. (function (BABYLON) {
  38631. var FilterPostProcess = (function (_super) {
  38632. __extends(FilterPostProcess, _super);
  38633. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  38634. var _this = this;
  38635. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  38636. this.kernelMatrix = kernelMatrix;
  38637. this.onApply = function (effect) {
  38638. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  38639. };
  38640. }
  38641. return FilterPostProcess;
  38642. })(BABYLON.PostProcess);
  38643. BABYLON.FilterPostProcess = FilterPostProcess;
  38644. })(BABYLON || (BABYLON = {}));
  38645. var BABYLON;
  38646. (function (BABYLON) {
  38647. var FxaaPostProcess = (function (_super) {
  38648. __extends(FxaaPostProcess, _super);
  38649. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38650. var _this = this;
  38651. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  38652. this.onSizeChanged = function () {
  38653. _this.texelWidth = 1.0 / _this.width;
  38654. _this.texelHeight = 1.0 / _this.height;
  38655. };
  38656. this.onApply = function (effect) {
  38657. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  38658. };
  38659. }
  38660. return FxaaPostProcess;
  38661. })(BABYLON.PostProcess);
  38662. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38663. })(BABYLON || (BABYLON = {}));
  38664. var BABYLON;
  38665. (function (BABYLON) {
  38666. var StereoscopicInterlacePostProcess = (function (_super) {
  38667. __extends(StereoscopicInterlacePostProcess, _super);
  38668. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  38669. var _this = this;
  38670. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  38671. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  38672. this.onSizeChanged = function () {
  38673. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  38674. };
  38675. this.onApply = function (effect) {
  38676. effect.setTextureFromPostProcess("camASampler", postProcessA);
  38677. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  38678. };
  38679. }
  38680. return StereoscopicInterlacePostProcess;
  38681. })(BABYLON.PostProcess);
  38682. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  38683. })(BABYLON || (BABYLON = {}));
  38684. var BABYLON;
  38685. (function (BABYLON) {
  38686. var LensFlare = (function () {
  38687. function LensFlare(size, position, color, imgUrl, system) {
  38688. this.size = size;
  38689. this.position = position;
  38690. this.dispose = function () {
  38691. if (this.texture) {
  38692. this.texture.dispose();
  38693. }
  38694. // Remove from scene
  38695. var index = this._system.lensFlares.indexOf(this);
  38696. this._system.lensFlares.splice(index, 1);
  38697. };
  38698. this.color = color || new BABYLON.Color3(1, 1, 1);
  38699. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  38700. this._system = system;
  38701. system.lensFlares.push(this);
  38702. }
  38703. return LensFlare;
  38704. })();
  38705. BABYLON.LensFlare = LensFlare;
  38706. })(BABYLON || (BABYLON = {}));
  38707. var BABYLON;
  38708. (function (BABYLON) {
  38709. var LensFlareSystem = (function () {
  38710. function LensFlareSystem(name, emitter, scene) {
  38711. this.name = name;
  38712. this.lensFlares = new Array();
  38713. this.borderLimit = 300;
  38714. this.layerMask = 0x0FFFFFFF;
  38715. this._vertexDeclaration = [2];
  38716. this._vertexStrideSize = 2 * 4;
  38717. this._isEnabled = true;
  38718. this._scene = scene;
  38719. this._emitter = emitter;
  38720. this.id = name;
  38721. scene.lensFlareSystems.push(this);
  38722. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  38723. // VBO
  38724. var vertices = [];
  38725. vertices.push(1, 1);
  38726. vertices.push(-1, 1);
  38727. vertices.push(-1, -1);
  38728. vertices.push(1, -1);
  38729. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  38730. // Indices
  38731. var indices = [];
  38732. indices.push(0);
  38733. indices.push(1);
  38734. indices.push(2);
  38735. indices.push(0);
  38736. indices.push(2);
  38737. indices.push(3);
  38738. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38739. // Effects
  38740. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  38741. }
  38742. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  38743. get: function () {
  38744. return this._isEnabled;
  38745. },
  38746. set: function (value) {
  38747. this._isEnabled = value;
  38748. },
  38749. enumerable: true,
  38750. configurable: true
  38751. });
  38752. LensFlareSystem.prototype.getScene = function () {
  38753. return this._scene;
  38754. };
  38755. LensFlareSystem.prototype.getEmitter = function () {
  38756. return this._emitter;
  38757. };
  38758. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  38759. this._emitter = newEmitter;
  38760. };
  38761. LensFlareSystem.prototype.getEmitterPosition = function () {
  38762. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  38763. };
  38764. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  38765. var position = this.getEmitterPosition();
  38766. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  38767. this._positionX = position.x;
  38768. this._positionY = position.y;
  38769. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  38770. if (position.z > 0) {
  38771. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  38772. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  38773. return true;
  38774. }
  38775. }
  38776. return false;
  38777. };
  38778. LensFlareSystem.prototype._isVisible = function () {
  38779. if (!this._isEnabled) {
  38780. return false;
  38781. }
  38782. var emitterPosition = this.getEmitterPosition();
  38783. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  38784. var distance = direction.length();
  38785. direction.normalize();
  38786. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  38787. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  38788. return !pickInfo.hit || pickInfo.distance > distance;
  38789. };
  38790. LensFlareSystem.prototype.render = function () {
  38791. if (!this._effect.isReady())
  38792. return false;
  38793. var engine = this._scene.getEngine();
  38794. var viewport = this._scene.activeCamera.viewport;
  38795. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  38796. // Position
  38797. if (!this.computeEffectivePosition(globalViewport)) {
  38798. return false;
  38799. }
  38800. // Visibility
  38801. if (!this._isVisible()) {
  38802. return false;
  38803. }
  38804. // Intensity
  38805. var awayX;
  38806. var awayY;
  38807. if (this._positionX < this.borderLimit + globalViewport.x) {
  38808. awayX = this.borderLimit + globalViewport.x - this._positionX;
  38809. }
  38810. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  38811. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  38812. }
  38813. else {
  38814. awayX = 0;
  38815. }
  38816. if (this._positionY < this.borderLimit + globalViewport.y) {
  38817. awayY = this.borderLimit + globalViewport.y - this._positionY;
  38818. }
  38819. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  38820. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  38821. }
  38822. else {
  38823. awayY = 0;
  38824. }
  38825. var away = (awayX > awayY) ? awayX : awayY;
  38826. if (away > this.borderLimit) {
  38827. away = this.borderLimit;
  38828. }
  38829. var intensity = 1.0 - (away / this.borderLimit);
  38830. if (intensity < 0) {
  38831. return false;
  38832. }
  38833. if (intensity > 1.0) {
  38834. intensity = 1.0;
  38835. }
  38836. // Position
  38837. var centerX = globalViewport.x + globalViewport.width / 2;
  38838. var centerY = globalViewport.y + globalViewport.height / 2;
  38839. var distX = centerX - this._positionX;
  38840. var distY = centerY - this._positionY;
  38841. // Effects
  38842. engine.enableEffect(this._effect);
  38843. engine.setState(false);
  38844. engine.setDepthBuffer(false);
  38845. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38846. // VBOs
  38847. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  38848. // Flares
  38849. for (var index = 0; index < this.lensFlares.length; index++) {
  38850. var flare = this.lensFlares[index];
  38851. var x = centerX - (distX * flare.position);
  38852. var y = centerY - (distY * flare.position);
  38853. var cw = flare.size;
  38854. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  38855. var cx = 2 * (x / globalViewport.width) - 1.0;
  38856. var cy = 1.0 - 2 * (y / globalViewport.height);
  38857. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  38858. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  38859. // Texture
  38860. this._effect.setTexture("textureSampler", flare.texture);
  38861. // Color
  38862. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  38863. // Draw order
  38864. engine.draw(true, 0, 6);
  38865. }
  38866. engine.setDepthBuffer(true);
  38867. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38868. return true;
  38869. };
  38870. LensFlareSystem.prototype.dispose = function () {
  38871. if (this._vertexBuffer) {
  38872. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  38873. this._vertexBuffer = null;
  38874. }
  38875. if (this._indexBuffer) {
  38876. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38877. this._indexBuffer = null;
  38878. }
  38879. while (this.lensFlares.length) {
  38880. this.lensFlares[0].dispose();
  38881. }
  38882. // Remove from scene
  38883. var index = this._scene.lensFlareSystems.indexOf(this);
  38884. this._scene.lensFlareSystems.splice(index, 1);
  38885. };
  38886. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  38887. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  38888. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  38889. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  38890. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  38891. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  38892. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  38893. var parsedFlare = parsedLensFlareSystem.flares[index];
  38894. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  38895. }
  38896. return lensFlareSystem;
  38897. };
  38898. LensFlareSystem.prototype.serialize = function () {
  38899. var serializationObject = {};
  38900. serializationObject.id = this.id;
  38901. serializationObject.name = this.name;
  38902. serializationObject.emitterId = this.getEmitter().id;
  38903. serializationObject.borderLimit = this.borderLimit;
  38904. serializationObject.flares = [];
  38905. for (var index = 0; index < this.lensFlares.length; index++) {
  38906. var flare = this.lensFlares[index];
  38907. serializationObject.flares.push({
  38908. size: flare.size,
  38909. position: flare.position,
  38910. color: flare.color.asArray(),
  38911. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  38912. });
  38913. }
  38914. return serializationObject;
  38915. };
  38916. return LensFlareSystem;
  38917. })();
  38918. BABYLON.LensFlareSystem = LensFlareSystem;
  38919. })(BABYLON || (BABYLON = {}));
  38920. var BABYLON;
  38921. (function (BABYLON) {
  38922. // We're mainly based on the logic defined into the FreeCamera code
  38923. var DeviceOrientationCamera = (function (_super) {
  38924. __extends(DeviceOrientationCamera, _super);
  38925. //-- end properties for backward compatibility for inputs
  38926. function DeviceOrientationCamera(name, position, scene) {
  38927. _super.call(this, name, position, scene);
  38928. this.inputs.addDeviceOrientation();
  38929. }
  38930. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  38931. //-- Begin properties for backward compatibility for inputs
  38932. get: function () {
  38933. var gamepad = this.inputs.attached["deviceOrientation"];
  38934. if (gamepad)
  38935. return gamepad.angularSensibility;
  38936. },
  38937. set: function (value) {
  38938. var gamepad = this.inputs.attached["deviceOrientation"];
  38939. if (gamepad)
  38940. gamepad.angularSensibility = value;
  38941. },
  38942. enumerable: true,
  38943. configurable: true
  38944. });
  38945. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  38946. get: function () {
  38947. var gamepad = this.inputs.attached["deviceOrientation"];
  38948. if (gamepad)
  38949. return gamepad.moveSensibility;
  38950. },
  38951. set: function (value) {
  38952. var gamepad = this.inputs.attached["deviceOrientation"];
  38953. if (gamepad)
  38954. gamepad.moveSensibility = value;
  38955. },
  38956. enumerable: true,
  38957. configurable: true
  38958. });
  38959. DeviceOrientationCamera.prototype.getTypeName = function () {
  38960. return "DeviceOrientationCamera";
  38961. };
  38962. return DeviceOrientationCamera;
  38963. })(BABYLON.FreeCamera);
  38964. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  38965. })(BABYLON || (BABYLON = {}));
  38966. var BABYLON;
  38967. (function (BABYLON) {
  38968. // We're mainly based on the logic defined into the FreeCamera code
  38969. var UniversalCamera = (function (_super) {
  38970. __extends(UniversalCamera, _super);
  38971. //-- end properties for backward compatibility for inputs
  38972. function UniversalCamera(name, position, scene) {
  38973. _super.call(this, name, position, scene);
  38974. this.inputs.addGamepad();
  38975. }
  38976. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  38977. //-- Begin properties for backward compatibility for inputs
  38978. get: function () {
  38979. var gamepad = this.inputs.attached["gamepad"];
  38980. if (gamepad)
  38981. return gamepad.gamepadAngularSensibility;
  38982. },
  38983. set: function (value) {
  38984. var gamepad = this.inputs.attached["gamepad"];
  38985. if (gamepad)
  38986. gamepad.gamepadAngularSensibility = value;
  38987. },
  38988. enumerable: true,
  38989. configurable: true
  38990. });
  38991. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  38992. get: function () {
  38993. var gamepad = this.inputs.attached["gamepad"];
  38994. if (gamepad)
  38995. return gamepad.gamepadMoveSensibility;
  38996. },
  38997. set: function (value) {
  38998. var gamepad = this.inputs.attached["gamepad"];
  38999. if (gamepad)
  39000. gamepad.gamepadMoveSensibility = value;
  39001. },
  39002. enumerable: true,
  39003. configurable: true
  39004. });
  39005. UniversalCamera.prototype.getTypeName = function () {
  39006. return "UniversalCamera";
  39007. };
  39008. return UniversalCamera;
  39009. })(BABYLON.TouchCamera);
  39010. BABYLON.UniversalCamera = UniversalCamera;
  39011. })(BABYLON || (BABYLON = {}));
  39012. var BABYLON;
  39013. (function (BABYLON) {
  39014. var Gamepads = (function () {
  39015. function Gamepads(ongamedpadconnected) {
  39016. var _this = this;
  39017. this.babylonGamepads = [];
  39018. this.oneGamepadConnected = false;
  39019. this.isMonitoring = false;
  39020. this.gamepadEventSupported = 'GamepadEvent' in window;
  39021. this.gamepadSupportAvailable = (navigator.getGamepads ||
  39022. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  39023. this._callbackGamepadConnected = ongamedpadconnected;
  39024. if (this.gamepadSupportAvailable) {
  39025. // Checking if the gamepad connected event is supported (like in Firefox)
  39026. if (this.gamepadEventSupported) {
  39027. this._onGamepadConnectedEvent = function (evt) {
  39028. _this._onGamepadConnected(evt);
  39029. };
  39030. this._onGamepadDisonnectedEvent = function (evt) {
  39031. _this._onGamepadDisconnected(evt);
  39032. };
  39033. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  39034. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  39035. }
  39036. else {
  39037. this._startMonitoringGamepads();
  39038. }
  39039. }
  39040. }
  39041. Gamepads.prototype.dispose = function () {
  39042. if (Gamepads.gamepadDOMInfo) {
  39043. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39044. }
  39045. if (this._onGamepadConnectedEvent) {
  39046. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  39047. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  39048. this._onGamepadConnectedEvent = null;
  39049. this._onGamepadDisonnectedEvent = null;
  39050. }
  39051. };
  39052. Gamepads.prototype._onGamepadConnected = function (evt) {
  39053. var newGamepad = this._addNewGamepad(evt.gamepad);
  39054. if (this._callbackGamepadConnected)
  39055. this._callbackGamepadConnected(newGamepad);
  39056. this._startMonitoringGamepads();
  39057. };
  39058. Gamepads.prototype._addNewGamepad = function (gamepad) {
  39059. if (!this.oneGamepadConnected) {
  39060. this.oneGamepadConnected = true;
  39061. if (Gamepads.gamepadDOMInfo) {
  39062. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39063. Gamepads.gamepadDOMInfo = null;
  39064. }
  39065. }
  39066. var newGamepad;
  39067. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  39068. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  39069. }
  39070. else {
  39071. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  39072. }
  39073. this.babylonGamepads.push(newGamepad);
  39074. return newGamepad;
  39075. };
  39076. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  39077. // Remove the gamepad from the list of gamepads to monitor.
  39078. for (var i in this.babylonGamepads) {
  39079. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  39080. this.babylonGamepads.splice(+i, 1);
  39081. break;
  39082. }
  39083. }
  39084. // If no gamepads are left, stop the polling loop.
  39085. if (this.babylonGamepads.length == 0) {
  39086. this._stopMonitoringGamepads();
  39087. }
  39088. };
  39089. Gamepads.prototype._startMonitoringGamepads = function () {
  39090. if (!this.isMonitoring) {
  39091. this.isMonitoring = true;
  39092. this._checkGamepadsStatus();
  39093. }
  39094. };
  39095. Gamepads.prototype._stopMonitoringGamepads = function () {
  39096. this.isMonitoring = false;
  39097. };
  39098. Gamepads.prototype._checkGamepadsStatus = function () {
  39099. var _this = this;
  39100. // updating gamepad objects
  39101. this._updateGamepadObjects();
  39102. for (var i in this.babylonGamepads) {
  39103. this.babylonGamepads[i].update();
  39104. }
  39105. if (this.isMonitoring) {
  39106. if (window.requestAnimationFrame) {
  39107. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39108. }
  39109. else if (window.mozRequestAnimationFrame) {
  39110. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39111. }
  39112. else if (window.webkitRequestAnimationFrame) {
  39113. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39114. }
  39115. }
  39116. };
  39117. // This function is called only on Chrome, which does not yet support
  39118. // connection/disconnection events, but requires you to monitor
  39119. // an array for changes.
  39120. Gamepads.prototype._updateGamepadObjects = function () {
  39121. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  39122. for (var i = 0; i < gamepads.length; i++) {
  39123. if (gamepads[i]) {
  39124. if (!(gamepads[i].index in this.babylonGamepads)) {
  39125. var newGamepad = this._addNewGamepad(gamepads[i]);
  39126. if (this._callbackGamepadConnected) {
  39127. this._callbackGamepadConnected(newGamepad);
  39128. }
  39129. }
  39130. else {
  39131. this.babylonGamepads[i].browserGamepad = gamepads[i];
  39132. }
  39133. }
  39134. }
  39135. };
  39136. return Gamepads;
  39137. })();
  39138. BABYLON.Gamepads = Gamepads;
  39139. var StickValues = (function () {
  39140. function StickValues(x, y) {
  39141. this.x = x;
  39142. this.y = y;
  39143. }
  39144. return StickValues;
  39145. })();
  39146. BABYLON.StickValues = StickValues;
  39147. var Gamepad = (function () {
  39148. function Gamepad(id, index, browserGamepad) {
  39149. this.id = id;
  39150. this.index = index;
  39151. this.browserGamepad = browserGamepad;
  39152. if (this.browserGamepad.axes.length >= 2) {
  39153. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39154. }
  39155. if (this.browserGamepad.axes.length >= 4) {
  39156. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39157. }
  39158. }
  39159. Gamepad.prototype.onleftstickchanged = function (callback) {
  39160. this._onleftstickchanged = callback;
  39161. };
  39162. Gamepad.prototype.onrightstickchanged = function (callback) {
  39163. this._onrightstickchanged = callback;
  39164. };
  39165. Object.defineProperty(Gamepad.prototype, "leftStick", {
  39166. get: function () {
  39167. return this._leftStick;
  39168. },
  39169. set: function (newValues) {
  39170. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  39171. this._onleftstickchanged(newValues);
  39172. }
  39173. this._leftStick = newValues;
  39174. },
  39175. enumerable: true,
  39176. configurable: true
  39177. });
  39178. Object.defineProperty(Gamepad.prototype, "rightStick", {
  39179. get: function () {
  39180. return this._rightStick;
  39181. },
  39182. set: function (newValues) {
  39183. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  39184. this._onrightstickchanged(newValues);
  39185. }
  39186. this._rightStick = newValues;
  39187. },
  39188. enumerable: true,
  39189. configurable: true
  39190. });
  39191. Gamepad.prototype.update = function () {
  39192. if (this._leftStick) {
  39193. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39194. }
  39195. if (this._rightStick) {
  39196. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39197. }
  39198. };
  39199. return Gamepad;
  39200. })();
  39201. BABYLON.Gamepad = Gamepad;
  39202. var GenericPad = (function (_super) {
  39203. __extends(GenericPad, _super);
  39204. function GenericPad(id, index, gamepad) {
  39205. _super.call(this, id, index, gamepad);
  39206. this.id = id;
  39207. this.index = index;
  39208. this.gamepad = gamepad;
  39209. this._buttons = new Array(gamepad.buttons.length);
  39210. }
  39211. GenericPad.prototype.onbuttondown = function (callback) {
  39212. this._onbuttondown = callback;
  39213. };
  39214. GenericPad.prototype.onbuttonup = function (callback) {
  39215. this._onbuttonup = callback;
  39216. };
  39217. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  39218. if (newValue !== currentValue) {
  39219. if (this._onbuttondown && newValue === 1) {
  39220. this._onbuttondown(buttonIndex);
  39221. }
  39222. if (this._onbuttonup && newValue === 0) {
  39223. this._onbuttonup(buttonIndex);
  39224. }
  39225. }
  39226. return newValue;
  39227. };
  39228. GenericPad.prototype.update = function () {
  39229. _super.prototype.update.call(this);
  39230. for (var index = 0; index < this._buttons.length; index++) {
  39231. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  39232. }
  39233. };
  39234. return GenericPad;
  39235. })(Gamepad);
  39236. BABYLON.GenericPad = GenericPad;
  39237. (function (Xbox360Button) {
  39238. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  39239. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  39240. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  39241. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  39242. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  39243. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  39244. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  39245. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  39246. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  39247. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  39248. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  39249. var Xbox360Button = BABYLON.Xbox360Button;
  39250. (function (Xbox360Dpad) {
  39251. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  39252. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  39253. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  39254. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  39255. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  39256. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  39257. var Xbox360Pad = (function (_super) {
  39258. __extends(Xbox360Pad, _super);
  39259. function Xbox360Pad() {
  39260. _super.apply(this, arguments);
  39261. this._leftTrigger = 0;
  39262. this._rightTrigger = 0;
  39263. this._buttonA = 0;
  39264. this._buttonB = 0;
  39265. this._buttonX = 0;
  39266. this._buttonY = 0;
  39267. this._buttonBack = 0;
  39268. this._buttonStart = 0;
  39269. this._buttonLB = 0;
  39270. this._buttonRB = 0;
  39271. this._buttonLeftStick = 0;
  39272. this._buttonRightStick = 0;
  39273. this._dPadUp = 0;
  39274. this._dPadDown = 0;
  39275. this._dPadLeft = 0;
  39276. this._dPadRight = 0;
  39277. }
  39278. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  39279. this._onlefttriggerchanged = callback;
  39280. };
  39281. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  39282. this._onrighttriggerchanged = callback;
  39283. };
  39284. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  39285. get: function () {
  39286. return this._leftTrigger;
  39287. },
  39288. set: function (newValue) {
  39289. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  39290. this._onlefttriggerchanged(newValue);
  39291. }
  39292. this._leftTrigger = newValue;
  39293. },
  39294. enumerable: true,
  39295. configurable: true
  39296. });
  39297. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  39298. get: function () {
  39299. return this._rightTrigger;
  39300. },
  39301. set: function (newValue) {
  39302. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  39303. this._onrighttriggerchanged(newValue);
  39304. }
  39305. this._rightTrigger = newValue;
  39306. },
  39307. enumerable: true,
  39308. configurable: true
  39309. });
  39310. Xbox360Pad.prototype.onbuttondown = function (callback) {
  39311. this._onbuttondown = callback;
  39312. };
  39313. Xbox360Pad.prototype.onbuttonup = function (callback) {
  39314. this._onbuttonup = callback;
  39315. };
  39316. Xbox360Pad.prototype.ondpaddown = function (callback) {
  39317. this._ondpaddown = callback;
  39318. };
  39319. Xbox360Pad.prototype.ondpadup = function (callback) {
  39320. this._ondpadup = callback;
  39321. };
  39322. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  39323. if (newValue !== currentValue) {
  39324. if (this._onbuttondown && newValue === 1) {
  39325. this._onbuttondown(buttonType);
  39326. }
  39327. if (this._onbuttonup && newValue === 0) {
  39328. this._onbuttonup(buttonType);
  39329. }
  39330. }
  39331. return newValue;
  39332. };
  39333. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  39334. if (newValue !== currentValue) {
  39335. if (this._ondpaddown && newValue === 1) {
  39336. this._ondpaddown(buttonType);
  39337. }
  39338. if (this._ondpadup && newValue === 0) {
  39339. this._ondpadup(buttonType);
  39340. }
  39341. }
  39342. return newValue;
  39343. };
  39344. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  39345. get: function () {
  39346. return this._buttonA;
  39347. },
  39348. set: function (value) {
  39349. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  39350. },
  39351. enumerable: true,
  39352. configurable: true
  39353. });
  39354. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  39355. get: function () {
  39356. return this._buttonB;
  39357. },
  39358. set: function (value) {
  39359. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  39360. },
  39361. enumerable: true,
  39362. configurable: true
  39363. });
  39364. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  39365. get: function () {
  39366. return this._buttonX;
  39367. },
  39368. set: function (value) {
  39369. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  39370. },
  39371. enumerable: true,
  39372. configurable: true
  39373. });
  39374. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  39375. get: function () {
  39376. return this._buttonY;
  39377. },
  39378. set: function (value) {
  39379. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  39380. },
  39381. enumerable: true,
  39382. configurable: true
  39383. });
  39384. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  39385. get: function () {
  39386. return this._buttonStart;
  39387. },
  39388. set: function (value) {
  39389. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39390. },
  39391. enumerable: true,
  39392. configurable: true
  39393. });
  39394. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39395. get: function () {
  39396. return this._buttonBack;
  39397. },
  39398. set: function (value) {
  39399. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39400. },
  39401. enumerable: true,
  39402. configurable: true
  39403. });
  39404. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39405. get: function () {
  39406. return this._buttonLB;
  39407. },
  39408. set: function (value) {
  39409. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39410. },
  39411. enumerable: true,
  39412. configurable: true
  39413. });
  39414. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39415. get: function () {
  39416. return this._buttonRB;
  39417. },
  39418. set: function (value) {
  39419. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39420. },
  39421. enumerable: true,
  39422. configurable: true
  39423. });
  39424. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39425. get: function () {
  39426. return this._buttonLeftStick;
  39427. },
  39428. set: function (value) {
  39429. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39430. },
  39431. enumerable: true,
  39432. configurable: true
  39433. });
  39434. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39435. get: function () {
  39436. return this._buttonRightStick;
  39437. },
  39438. set: function (value) {
  39439. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39440. },
  39441. enumerable: true,
  39442. configurable: true
  39443. });
  39444. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39445. get: function () {
  39446. return this._dPadUp;
  39447. },
  39448. set: function (value) {
  39449. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39450. },
  39451. enumerable: true,
  39452. configurable: true
  39453. });
  39454. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39455. get: function () {
  39456. return this._dPadDown;
  39457. },
  39458. set: function (value) {
  39459. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39460. },
  39461. enumerable: true,
  39462. configurable: true
  39463. });
  39464. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39465. get: function () {
  39466. return this._dPadLeft;
  39467. },
  39468. set: function (value) {
  39469. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39470. },
  39471. enumerable: true,
  39472. configurable: true
  39473. });
  39474. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39475. get: function () {
  39476. return this._dPadRight;
  39477. },
  39478. set: function (value) {
  39479. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39480. },
  39481. enumerable: true,
  39482. configurable: true
  39483. });
  39484. Xbox360Pad.prototype.update = function () {
  39485. _super.prototype.update.call(this);
  39486. this.buttonA = this.browserGamepad.buttons[0].value;
  39487. this.buttonB = this.browserGamepad.buttons[1].value;
  39488. this.buttonX = this.browserGamepad.buttons[2].value;
  39489. this.buttonY = this.browserGamepad.buttons[3].value;
  39490. this.buttonLB = this.browserGamepad.buttons[4].value;
  39491. this.buttonRB = this.browserGamepad.buttons[5].value;
  39492. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39493. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39494. this.buttonBack = this.browserGamepad.buttons[8].value;
  39495. this.buttonStart = this.browserGamepad.buttons[9].value;
  39496. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39497. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39498. this.dPadUp = this.browserGamepad.buttons[12].value;
  39499. this.dPadDown = this.browserGamepad.buttons[13].value;
  39500. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39501. this.dPadRight = this.browserGamepad.buttons[15].value;
  39502. };
  39503. return Xbox360Pad;
  39504. })(Gamepad);
  39505. BABYLON.Xbox360Pad = Xbox360Pad;
  39506. })(BABYLON || (BABYLON = {}));
  39507. var BABYLON;
  39508. (function (BABYLON) {
  39509. // We're mainly based on the logic defined into the FreeCamera code
  39510. var GamepadCamera = (function (_super) {
  39511. __extends(GamepadCamera, _super);
  39512. //-- end properties for backward compatibility for inputs
  39513. function GamepadCamera(name, position, scene) {
  39514. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39515. _super.call(this, name, position, scene);
  39516. }
  39517. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  39518. //-- Begin properties for backward compatibility for inputs
  39519. get: function () {
  39520. var gamepad = this.inputs.attached["gamepad"];
  39521. if (gamepad)
  39522. return gamepad.gamepadAngularSensibility;
  39523. },
  39524. set: function (value) {
  39525. var gamepad = this.inputs.attached["gamepad"];
  39526. if (gamepad)
  39527. gamepad.gamepadAngularSensibility = value;
  39528. },
  39529. enumerable: true,
  39530. configurable: true
  39531. });
  39532. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  39533. get: function () {
  39534. var gamepad = this.inputs.attached["gamepad"];
  39535. if (gamepad)
  39536. return gamepad.gamepadMoveSensibility;
  39537. },
  39538. set: function (value) {
  39539. var gamepad = this.inputs.attached["gamepad"];
  39540. if (gamepad)
  39541. gamepad.gamepadMoveSensibility = value;
  39542. },
  39543. enumerable: true,
  39544. configurable: true
  39545. });
  39546. GamepadCamera.prototype.getTypeName = function () {
  39547. return "GamepadCamera";
  39548. };
  39549. return GamepadCamera;
  39550. })(BABYLON.UniversalCamera);
  39551. BABYLON.GamepadCamera = GamepadCamera;
  39552. })(BABYLON || (BABYLON = {}));
  39553. var BABYLON;
  39554. (function (BABYLON) {
  39555. var Analyser = (function () {
  39556. function Analyser(scene) {
  39557. this.SMOOTHING = 0.75;
  39558. this.FFT_SIZE = 512;
  39559. this.BARGRAPHAMPLITUDE = 256;
  39560. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39561. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39562. this._scene = scene;
  39563. this._audioEngine = BABYLON.Engine.audioEngine;
  39564. if (this._audioEngine.canUseWebAudio) {
  39565. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39566. this._webAudioAnalyser.minDecibels = -140;
  39567. this._webAudioAnalyser.maxDecibels = 0;
  39568. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39569. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39570. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39571. }
  39572. }
  39573. Analyser.prototype.getFrequencyBinCount = function () {
  39574. if (this._audioEngine.canUseWebAudio) {
  39575. return this._webAudioAnalyser.frequencyBinCount;
  39576. }
  39577. else {
  39578. return 0;
  39579. }
  39580. };
  39581. Analyser.prototype.getByteFrequencyData = function () {
  39582. if (this._audioEngine.canUseWebAudio) {
  39583. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39584. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39585. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  39586. }
  39587. return this._byteFreqs;
  39588. };
  39589. Analyser.prototype.getByteTimeDomainData = function () {
  39590. if (this._audioEngine.canUseWebAudio) {
  39591. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39592. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39593. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  39594. }
  39595. return this._byteTime;
  39596. };
  39597. Analyser.prototype.getFloatFrequencyData = function () {
  39598. if (this._audioEngine.canUseWebAudio) {
  39599. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39600. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39601. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  39602. }
  39603. return this._floatFreqs;
  39604. };
  39605. Analyser.prototype.drawDebugCanvas = function () {
  39606. var _this = this;
  39607. if (this._audioEngine.canUseWebAudio) {
  39608. if (!this._debugCanvas) {
  39609. this._debugCanvas = document.createElement("canvas");
  39610. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  39611. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  39612. this._debugCanvas.style.position = "absolute";
  39613. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  39614. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  39615. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  39616. document.body.appendChild(this._debugCanvas);
  39617. this._registerFunc = function () {
  39618. _this.drawDebugCanvas();
  39619. };
  39620. this._scene.registerBeforeRender(this._registerFunc);
  39621. }
  39622. if (this._registerFunc) {
  39623. var workingArray = this.getByteFrequencyData();
  39624. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  39625. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  39626. // Draw the frequency domain chart.
  39627. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  39628. var value = workingArray[i];
  39629. var percent = value / this.BARGRAPHAMPLITUDE;
  39630. var height = this.DEBUGCANVASSIZE.height * percent;
  39631. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  39632. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  39633. var hue = i / this.getFrequencyBinCount() * 360;
  39634. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  39635. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  39636. }
  39637. }
  39638. }
  39639. };
  39640. Analyser.prototype.stopDebugCanvas = function () {
  39641. if (this._debugCanvas) {
  39642. this._scene.unregisterBeforeRender(this._registerFunc);
  39643. this._registerFunc = null;
  39644. document.body.removeChild(this._debugCanvas);
  39645. this._debugCanvas = null;
  39646. this._debugCanvasContext = null;
  39647. }
  39648. };
  39649. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39650. if (this._audioEngine.canUseWebAudio) {
  39651. inputAudioNode.connect(this._webAudioAnalyser);
  39652. this._webAudioAnalyser.connect(outputAudioNode);
  39653. }
  39654. };
  39655. Analyser.prototype.dispose = function () {
  39656. if (this._audioEngine.canUseWebAudio) {
  39657. this._webAudioAnalyser.disconnect();
  39658. }
  39659. };
  39660. return Analyser;
  39661. })();
  39662. BABYLON.Analyser = Analyser;
  39663. })(BABYLON || (BABYLON = {}));
  39664. var BABYLON;
  39665. (function (BABYLON) {
  39666. var DepthRenderer = (function () {
  39667. function DepthRenderer(scene, type) {
  39668. var _this = this;
  39669. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  39670. this._viewMatrix = BABYLON.Matrix.Zero();
  39671. this._projectionMatrix = BABYLON.Matrix.Zero();
  39672. this._transformMatrix = BABYLON.Matrix.Zero();
  39673. this._worldViewProjection = BABYLON.Matrix.Zero();
  39674. this._scene = scene;
  39675. var engine = scene.getEngine();
  39676. // Render target
  39677. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  39678. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39679. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39680. this._depthMap.refreshRate = 1;
  39681. this._depthMap.renderParticles = false;
  39682. this._depthMap.renderList = null;
  39683. // set default depth value to 1.0 (far away)
  39684. this._depthMap.onClear = function (engine) {
  39685. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  39686. };
  39687. // Custom render function
  39688. var renderSubMesh = function (subMesh) {
  39689. var mesh = subMesh.getRenderingMesh();
  39690. var scene = _this._scene;
  39691. var engine = scene.getEngine();
  39692. // Culling
  39693. engine.setState(subMesh.getMaterial().backFaceCulling);
  39694. // Managing instances
  39695. var batch = mesh._getInstancesRenderList(subMesh._id);
  39696. if (batch.mustReturn) {
  39697. return;
  39698. }
  39699. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39700. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39701. engine.enableEffect(_this._effect);
  39702. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  39703. var material = subMesh.getMaterial();
  39704. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  39705. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  39706. // Alpha test
  39707. if (material && material.needAlphaTesting()) {
  39708. var alphaTexture = material.getAlphaTestTexture();
  39709. _this._effect.setTexture("diffuseSampler", alphaTexture);
  39710. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39711. }
  39712. // Bones
  39713. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39714. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39715. }
  39716. // Draw
  39717. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  39718. }
  39719. };
  39720. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  39721. var index;
  39722. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39723. renderSubMesh(opaqueSubMeshes.data[index]);
  39724. }
  39725. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39726. renderSubMesh(alphaTestSubMeshes.data[index]);
  39727. }
  39728. };
  39729. }
  39730. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  39731. var material = subMesh.getMaterial();
  39732. if (material.disableDepthWrite) {
  39733. return false;
  39734. }
  39735. var defines = [];
  39736. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39737. var mesh = subMesh.getMesh();
  39738. var scene = mesh.getScene();
  39739. // Alpha test
  39740. if (material && material.needAlphaTesting()) {
  39741. defines.push("#define ALPHATEST");
  39742. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39743. attribs.push(BABYLON.VertexBuffer.UVKind);
  39744. defines.push("#define UV1");
  39745. }
  39746. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39747. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39748. defines.push("#define UV2");
  39749. }
  39750. }
  39751. // Bones
  39752. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39753. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39754. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39755. if (mesh.numBoneInfluencers > 4) {
  39756. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39757. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39758. }
  39759. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39760. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39761. }
  39762. else {
  39763. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39764. }
  39765. // Instances
  39766. if (useInstances) {
  39767. defines.push("#define INSTANCES");
  39768. attribs.push("world0");
  39769. attribs.push("world1");
  39770. attribs.push("world2");
  39771. attribs.push("world3");
  39772. }
  39773. // Get correct effect
  39774. var join = defines.join("\n");
  39775. if (this._cachedDefines !== join) {
  39776. this._cachedDefines = join;
  39777. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  39778. }
  39779. return this._effect.isReady();
  39780. };
  39781. DepthRenderer.prototype.getDepthMap = function () {
  39782. return this._depthMap;
  39783. };
  39784. // Methods
  39785. DepthRenderer.prototype.dispose = function () {
  39786. this._depthMap.dispose();
  39787. };
  39788. return DepthRenderer;
  39789. })();
  39790. BABYLON.DepthRenderer = DepthRenderer;
  39791. })(BABYLON || (BABYLON = {}));
  39792. var BABYLON;
  39793. (function (BABYLON) {
  39794. var SSAORenderingPipeline = (function (_super) {
  39795. __extends(SSAORenderingPipeline, _super);
  39796. /**
  39797. * @constructor
  39798. * @param {string} name - The rendering pipeline name
  39799. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39800. * @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 }
  39801. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39802. */
  39803. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  39804. var _this = this;
  39805. _super.call(this, scene.getEngine(), name);
  39806. // Members
  39807. /**
  39808. * The PassPostProcess id in the pipeline that contains the original scene color
  39809. * @type {string}
  39810. */
  39811. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  39812. /**
  39813. * The SSAO PostProcess id in the pipeline
  39814. * @type {string}
  39815. */
  39816. this.SSAORenderEffect = "SSAORenderEffect";
  39817. /**
  39818. * The horizontal blur PostProcess id in the pipeline
  39819. * @type {string}
  39820. */
  39821. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  39822. /**
  39823. * The vertical blur PostProcess id in the pipeline
  39824. * @type {string}
  39825. */
  39826. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  39827. /**
  39828. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  39829. * @type {string}
  39830. */
  39831. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  39832. /**
  39833. * The output strength of the SSAO post-process. Default value is 1.0.
  39834. * @type {number}
  39835. */
  39836. this.totalStrength = 1.0;
  39837. /**
  39838. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  39839. * @type {number}
  39840. */
  39841. this.radius = 0.0001;
  39842. /**
  39843. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  39844. * Must not be equal to fallOff and superior to fallOff.
  39845. * Default value is 0.975
  39846. * @type {number}
  39847. */
  39848. this.area = 0.0075;
  39849. /**
  39850. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  39851. * Must not be equal to area and inferior to area.
  39852. * Default value is 0.0
  39853. * @type {number}
  39854. */
  39855. this.fallOff = 0.000001;
  39856. /**
  39857. * The base color of the SSAO post-process
  39858. * The final result is "base + ssao" between [0, 1]
  39859. * @type {number}
  39860. */
  39861. this.base = 0.5;
  39862. this._firstUpdate = true;
  39863. this._scene = scene;
  39864. // Set up assets
  39865. this._createRandomTexture();
  39866. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  39867. var ssaoRatio = ratio.ssaoRatio || ratio;
  39868. var combineRatio = ratio.combineRatio || ratio;
  39869. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39870. this._createSSAOPostProcess(ssaoRatio);
  39871. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39872. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39873. this._createSSAOCombinePostProcess(combineRatio);
  39874. // Set up pipeline
  39875. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  39876. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  39877. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  39878. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  39879. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  39880. // Finish
  39881. scene.postProcessRenderPipelineManager.addPipeline(this);
  39882. if (cameras)
  39883. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39884. }
  39885. // Public Methods
  39886. /**
  39887. * Returns the horizontal blur PostProcess
  39888. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  39889. */
  39890. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  39891. return this._blurHPostProcess;
  39892. };
  39893. /**
  39894. * Returns the vertical blur PostProcess
  39895. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  39896. */
  39897. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  39898. return this._blurVPostProcess;
  39899. };
  39900. /**
  39901. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  39902. */
  39903. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  39904. if (disableDepthRender === void 0) { disableDepthRender = false; }
  39905. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39906. this._originalColorPostProcess = undefined;
  39907. this._ssaoPostProcess = undefined;
  39908. this._blurHPostProcess = undefined;
  39909. this._blurVPostProcess = undefined;
  39910. this._ssaoCombinePostProcess = undefined;
  39911. this._randomTexture.dispose();
  39912. if (disableDepthRender)
  39913. this._scene.disableDepthRenderer();
  39914. };
  39915. // Private Methods
  39916. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  39917. var _this = this;
  39918. var numSamples = 16;
  39919. var sampleSphere = [
  39920. 0.5381, 0.1856, -0.4319,
  39921. 0.1379, 0.2486, 0.4430,
  39922. 0.3371, 0.5679, -0.0057,
  39923. -0.6999, -0.0451, -0.0019,
  39924. 0.0689, -0.1598, -0.8547,
  39925. 0.0560, 0.0069, -0.1843,
  39926. -0.0146, 0.1402, 0.0762,
  39927. 0.0100, -0.1924, -0.0344,
  39928. -0.3577, -0.5301, -0.4358,
  39929. -0.3169, 0.1063, 0.0158,
  39930. 0.0103, -0.5869, 0.0046,
  39931. -0.0897, -0.4940, 0.3287,
  39932. 0.7119, -0.0154, -0.0918,
  39933. -0.0533, 0.0596, -0.5411,
  39934. 0.0352, -0.0631, 0.5460,
  39935. -0.4776, 0.2847, -0.0271
  39936. ];
  39937. var samplesFactor = 1.0 / numSamples;
  39938. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  39939. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  39940. "area", "fallOff", "base"
  39941. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  39942. this._ssaoPostProcess.onApply = function (effect) {
  39943. if (_this._firstUpdate) {
  39944. effect.setArray3("sampleSphere", sampleSphere);
  39945. effect.setFloat("samplesFactor", samplesFactor);
  39946. effect.setFloat("randTextureTiles", 4.0);
  39947. _this._firstUpdate = false;
  39948. }
  39949. effect.setFloat("totalStrength", _this.totalStrength);
  39950. effect.setFloat("radius", _this.radius);
  39951. effect.setFloat("area", _this.area);
  39952. effect.setFloat("fallOff", _this.fallOff);
  39953. effect.setFloat("base", _this.base);
  39954. effect.setTexture("textureSampler", _this._depthTexture);
  39955. effect.setTexture("randomSampler", _this._randomTexture);
  39956. };
  39957. };
  39958. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  39959. var _this = this;
  39960. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39961. this._ssaoCombinePostProcess.onApply = function (effect) {
  39962. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  39963. };
  39964. };
  39965. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  39966. var size = 512;
  39967. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39968. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39969. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39970. var context = this._randomTexture.getContext();
  39971. var rand = function (min, max) {
  39972. return Math.random() * (max - min) + min;
  39973. };
  39974. var randVector = BABYLON.Vector3.Zero();
  39975. for (var x = 0; x < size; x++) {
  39976. for (var y = 0; y < size; y++) {
  39977. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  39978. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  39979. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  39980. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  39981. context.fillRect(x, y, 1, 1);
  39982. }
  39983. }
  39984. this._randomTexture.update(false);
  39985. };
  39986. return SSAORenderingPipeline;
  39987. })(BABYLON.PostProcessRenderPipeline);
  39988. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  39989. })(BABYLON || (BABYLON = {}));
  39990. var BABYLON;
  39991. (function (BABYLON) {
  39992. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  39993. var VolumetricLightScatteringPostProcess = (function (_super) {
  39994. __extends(VolumetricLightScatteringPostProcess, _super);
  39995. /**
  39996. * @constructor
  39997. * @param {string} name - The post-process name
  39998. * @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)
  39999. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  40000. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  40001. * @param {number} samples - The post-process quality, default 100
  40002. * @param {number} samplingMode - The post-process filtering mode
  40003. * @param {BABYLON.Engine} engine - The babylon engine
  40004. * @param {boolean} reusable - If the post-process is reusable
  40005. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  40006. */
  40007. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  40008. var _this = this;
  40009. if (samples === void 0) { samples = 100; }
  40010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40011. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  40012. this._screenCoordinates = BABYLON.Vector2.Zero();
  40013. /**
  40014. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  40015. * @type {Vector3}
  40016. */
  40017. this.customMeshPosition = BABYLON.Vector3.Zero();
  40018. /**
  40019. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  40020. * @type {boolean}
  40021. */
  40022. this.useCustomMeshPosition = false;
  40023. /**
  40024. * If the post-process should inverse the light scattering direction
  40025. * @type {boolean}
  40026. */
  40027. this.invert = true;
  40028. /**
  40029. * Array containing the excluded meshes not rendered in the internal pass
  40030. */
  40031. this.excludedMeshes = new Array();
  40032. /**
  40033. * Controls the overall intensity of the post-process
  40034. * @type {number}
  40035. */
  40036. this.exposure = 0.3;
  40037. /**
  40038. * Dissipates each sample's contribution in range [0, 1]
  40039. * @type {number}
  40040. */
  40041. this.decay = 0.96815;
  40042. /**
  40043. * Controls the overall intensity of each sample
  40044. * @type {number}
  40045. */
  40046. this.weight = 0.58767;
  40047. /**
  40048. * Controls the density of each sample
  40049. * @type {number}
  40050. */
  40051. this.density = 0.926;
  40052. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  40053. var engine = scene.getEngine();
  40054. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  40055. // Configure mesh
  40056. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  40057. // Configure
  40058. this._createPass(scene, ratio.passRatio || ratio);
  40059. this.onActivate = function (camera) {
  40060. if (!_this.isSupported) {
  40061. _this.dispose(camera);
  40062. }
  40063. _this.onActivate = null;
  40064. };
  40065. this.onApply = function (effect) {
  40066. _this._updateMeshScreenCoordinates(scene);
  40067. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  40068. effect.setFloat("exposure", _this.exposure);
  40069. effect.setFloat("decay", _this.decay);
  40070. effect.setFloat("weight", _this.weight);
  40071. effect.setFloat("density", _this.density);
  40072. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  40073. };
  40074. }
  40075. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  40076. get: function () {
  40077. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  40078. return false;
  40079. },
  40080. set: function (useDiffuseColor) {
  40081. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  40082. },
  40083. enumerable: true,
  40084. configurable: true
  40085. });
  40086. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  40087. var mesh = subMesh.getMesh();
  40088. // Render this.mesh as default
  40089. if (mesh === this.mesh) {
  40090. return mesh.material.isReady(mesh);
  40091. }
  40092. var defines = [];
  40093. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40094. var material = subMesh.getMaterial();
  40095. var needUV = false;
  40096. // Alpha test
  40097. if (material) {
  40098. if (material.needAlphaTesting()) {
  40099. defines.push("#define ALPHATEST");
  40100. }
  40101. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40102. attribs.push(BABYLON.VertexBuffer.UVKind);
  40103. defines.push("#define UV1");
  40104. }
  40105. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40106. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40107. defines.push("#define UV2");
  40108. }
  40109. }
  40110. // Bones
  40111. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40112. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40113. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40114. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40115. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40116. }
  40117. else {
  40118. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40119. }
  40120. // Instances
  40121. if (useInstances) {
  40122. defines.push("#define INSTANCES");
  40123. attribs.push("world0");
  40124. attribs.push("world1");
  40125. attribs.push("world2");
  40126. attribs.push("world3");
  40127. }
  40128. // Get correct effect
  40129. var join = defines.join("\n");
  40130. if (this._cachedDefines !== join) {
  40131. this._cachedDefines = join;
  40132. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  40133. }
  40134. return this._volumetricLightScatteringPass.isReady();
  40135. };
  40136. /**
  40137. * Sets the new light position for light scattering effect
  40138. * @param {BABYLON.Vector3} The new custom light position
  40139. */
  40140. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  40141. this.customMeshPosition = position;
  40142. };
  40143. /**
  40144. * Returns the light position for light scattering effect
  40145. * @return {BABYLON.Vector3} The custom light position
  40146. */
  40147. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  40148. return this.customMeshPosition;
  40149. };
  40150. /**
  40151. * Disposes the internal assets and detaches the post-process from the camera
  40152. */
  40153. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  40154. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  40155. if (rttIndex !== -1) {
  40156. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  40157. }
  40158. this._volumetricLightScatteringRTT.dispose();
  40159. _super.prototype.dispose.call(this, camera);
  40160. };
  40161. /**
  40162. * Returns the render target texture used by the post-process
  40163. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  40164. */
  40165. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  40166. return this._volumetricLightScatteringRTT;
  40167. };
  40168. // Private methods
  40169. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  40170. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  40171. return true;
  40172. }
  40173. return false;
  40174. };
  40175. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  40176. var _this = this;
  40177. var engine = scene.getEngine();
  40178. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  40179. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40180. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40181. this._volumetricLightScatteringRTT.renderList = null;
  40182. this._volumetricLightScatteringRTT.renderParticles = false;
  40183. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  40184. // Custom render function for submeshes
  40185. var renderSubMesh = function (subMesh) {
  40186. var mesh = subMesh.getRenderingMesh();
  40187. if (_this._meshExcluded(mesh)) {
  40188. return;
  40189. }
  40190. var scene = mesh.getScene();
  40191. var engine = scene.getEngine();
  40192. // Culling
  40193. engine.setState(subMesh.getMaterial().backFaceCulling);
  40194. // Managing instances
  40195. var batch = mesh._getInstancesRenderList(subMesh._id);
  40196. if (batch.mustReturn) {
  40197. return;
  40198. }
  40199. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40200. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40201. var effect = _this._volumetricLightScatteringPass;
  40202. if (mesh === _this.mesh) {
  40203. effect = subMesh.getMaterial().getEffect();
  40204. }
  40205. engine.enableEffect(effect);
  40206. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  40207. if (mesh === _this.mesh) {
  40208. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  40209. }
  40210. else {
  40211. var material = subMesh.getMaterial();
  40212. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  40213. // Alpha test
  40214. if (material && material.needAlphaTesting()) {
  40215. var alphaTexture = material.getAlphaTestTexture();
  40216. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  40217. if (alphaTexture) {
  40218. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40219. }
  40220. }
  40221. // Bones
  40222. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40223. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40224. }
  40225. }
  40226. // Draw
  40227. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  40228. }
  40229. };
  40230. // Render target texture callbacks
  40231. var savedSceneClearColor;
  40232. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  40233. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  40234. savedSceneClearColor = scene.clearColor;
  40235. scene.clearColor = sceneClearColor;
  40236. };
  40237. this._volumetricLightScatteringRTT.onAfterRender = function () {
  40238. scene.clearColor = savedSceneClearColor;
  40239. };
  40240. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  40241. var engine = scene.getEngine();
  40242. var index;
  40243. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40244. renderSubMesh(opaqueSubMeshes.data[index]);
  40245. }
  40246. engine.setAlphaTesting(true);
  40247. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40248. renderSubMesh(alphaTestSubMeshes.data[index]);
  40249. }
  40250. engine.setAlphaTesting(false);
  40251. if (transparentSubMeshes.length) {
  40252. // Sort sub meshes
  40253. for (index = 0; index < transparentSubMeshes.length; index++) {
  40254. var submesh = transparentSubMeshes.data[index];
  40255. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  40256. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  40257. }
  40258. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  40259. sortedArray.sort(function (a, b) {
  40260. // Alpha index first
  40261. if (a._alphaIndex > b._alphaIndex) {
  40262. return 1;
  40263. }
  40264. if (a._alphaIndex < b._alphaIndex) {
  40265. return -1;
  40266. }
  40267. // Then distance to camera
  40268. if (a._distanceToCamera < b._distanceToCamera) {
  40269. return 1;
  40270. }
  40271. if (a._distanceToCamera > b._distanceToCamera) {
  40272. return -1;
  40273. }
  40274. return 0;
  40275. });
  40276. // Render sub meshes
  40277. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40278. for (index = 0; index < sortedArray.length; index++) {
  40279. renderSubMesh(sortedArray[index]);
  40280. }
  40281. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40282. }
  40283. };
  40284. };
  40285. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  40286. var transform = scene.getTransformMatrix();
  40287. var meshPosition;
  40288. if (this.useCustomMeshPosition) {
  40289. meshPosition = this.customMeshPosition;
  40290. }
  40291. else if (this.attachedNode) {
  40292. meshPosition = this.attachedNode.position;
  40293. }
  40294. else {
  40295. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  40296. }
  40297. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  40298. this._screenCoordinates.x = pos.x / this._viewPort.width;
  40299. this._screenCoordinates.y = pos.y / this._viewPort.height;
  40300. if (this.invert)
  40301. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  40302. };
  40303. // Static methods
  40304. /**
  40305. * Creates a default mesh for the Volumeric Light Scattering post-process
  40306. * @param {string} The mesh name
  40307. * @param {BABYLON.Scene} The scene where to create the mesh
  40308. * @return {BABYLON.Mesh} the default mesh
  40309. */
  40310. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  40311. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  40312. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  40313. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  40314. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  40315. mesh.material = material;
  40316. return mesh;
  40317. };
  40318. __decorate([
  40319. BABYLON.serializeAsVector3()
  40320. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  40321. __decorate([
  40322. BABYLON.serialize()
  40323. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  40324. __decorate([
  40325. BABYLON.serialize()
  40326. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  40327. __decorate([
  40328. BABYLON.serializeAsMeshReference()
  40329. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  40330. __decorate([
  40331. BABYLON.serialize()
  40332. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  40333. __decorate([
  40334. BABYLON.serialize()
  40335. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  40336. __decorate([
  40337. BABYLON.serialize()
  40338. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  40339. __decorate([
  40340. BABYLON.serialize()
  40341. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  40342. __decorate([
  40343. BABYLON.serialize()
  40344. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  40345. return VolumetricLightScatteringPostProcess;
  40346. })(BABYLON.PostProcess);
  40347. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  40348. })(BABYLON || (BABYLON = {}));
  40349. // BABYLON.JS Chromatic Aberration GLSL Shader
  40350. // Author: Olivier Guyot
  40351. // Separates very slightly R, G and B colors on the edges of the screen
  40352. // Inspired by Francois Tarlier & Martins Upitis
  40353. var BABYLON;
  40354. (function (BABYLON) {
  40355. var LensRenderingPipeline = (function (_super) {
  40356. __extends(LensRenderingPipeline, _super);
  40357. /**
  40358. * @constructor
  40359. *
  40360. * Effect parameters are as follow:
  40361. * {
  40362. * chromatic_aberration: number; // from 0 to x (1 for realism)
  40363. * edge_blur: number; // from 0 to x (1 for realism)
  40364. * distortion: number; // from 0 to x (1 for realism)
  40365. * grain_amount: number; // from 0 to 1
  40366. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  40367. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  40368. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  40369. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  40370. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  40371. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  40372. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  40373. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  40374. * }
  40375. * Note: if an effect parameter is unset, effect is disabled
  40376. *
  40377. * @param {string} name - The rendering pipeline name
  40378. * @param {object} parameters - An object containing all parameters (see above)
  40379. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40380. * @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)
  40381. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40382. */
  40383. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  40384. var _this = this;
  40385. if (ratio === void 0) { ratio = 1.0; }
  40386. _super.call(this, scene.getEngine(), name);
  40387. // Lens effects can be of the following:
  40388. // - chromatic aberration (slight shift of RGB colors)
  40389. // - blur on the edge of the lens
  40390. // - lens distortion
  40391. // - depth-of-field blur & highlights enhancing
  40392. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  40393. // - grain effect (noise or custom texture)
  40394. // Two additional texture samplers are needed:
  40395. // - depth map (for depth-of-field)
  40396. // - grain texture
  40397. /**
  40398. * The chromatic aberration PostProcess id in the pipeline
  40399. * @type {string}
  40400. */
  40401. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  40402. /**
  40403. * The highlights enhancing PostProcess id in the pipeline
  40404. * @type {string}
  40405. */
  40406. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  40407. /**
  40408. * The depth-of-field PostProcess id in the pipeline
  40409. * @type {string}
  40410. */
  40411. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  40412. this._scene = scene;
  40413. // Fetch texture samplers
  40414. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40415. if (parameters.grain_texture) {
  40416. this._grainTexture = parameters.grain_texture;
  40417. }
  40418. else {
  40419. this._createGrainTexture();
  40420. }
  40421. // save parameters
  40422. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  40423. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  40424. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  40425. this._distortion = parameters.distortion ? parameters.distortion : 0;
  40426. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  40427. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  40428. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  40429. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  40430. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  40431. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  40432. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  40433. // Create effects
  40434. this._createChromaticAberrationPostProcess(ratio);
  40435. this._createHighlightsPostProcess(ratio);
  40436. this._createDepthOfFieldPostProcess(ratio / 4);
  40437. // Set up pipeline
  40438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  40439. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  40440. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  40441. if (this._highlightsGain === -1) {
  40442. this._disableEffect(this.HighlightsEnhancingEffect, null);
  40443. }
  40444. // Finish
  40445. scene.postProcessRenderPipelineManager.addPipeline(this);
  40446. if (cameras) {
  40447. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40448. }
  40449. }
  40450. // public methods (self explanatory)
  40451. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  40452. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  40453. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  40454. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  40455. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  40456. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  40457. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  40458. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  40459. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  40460. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  40461. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  40462. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  40463. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  40464. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  40465. };
  40466. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  40467. this._highlightsPostProcess.updateEffect();
  40468. };
  40469. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  40470. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  40471. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  40472. this._highlightsGain = amount;
  40473. };
  40474. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  40475. if (this._highlightsGain === -1) {
  40476. this._highlightsGain = 1.0;
  40477. }
  40478. this._highlightsThreshold = amount;
  40479. };
  40480. LensRenderingPipeline.prototype.disableHighlights = function () {
  40481. this._highlightsGain = -1;
  40482. };
  40483. /**
  40484. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  40485. */
  40486. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40487. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40488. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40489. this._chromaticAberrationPostProcess = undefined;
  40490. this._highlightsPostProcess = undefined;
  40491. this._depthOfFieldPostProcess = undefined;
  40492. this._grainTexture.dispose();
  40493. if (disableDepthRender)
  40494. this._scene.disableDepthRenderer();
  40495. };
  40496. // colors shifting and distortion
  40497. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  40498. var _this = this;
  40499. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  40500. [], // samplers
  40501. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40502. this._chromaticAberrationPostProcess.onApply = function (effect) {
  40503. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  40504. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40505. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40506. };
  40507. };
  40508. // highlights enhancing
  40509. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  40510. var _this = this;
  40511. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  40512. [], // samplers
  40513. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  40514. this._highlightsPostProcess.onApply = function (effect) {
  40515. effect.setFloat('gain', _this._highlightsGain);
  40516. effect.setFloat('threshold', _this._highlightsThreshold);
  40517. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  40518. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40519. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40520. };
  40521. };
  40522. // colors shifting and distortion
  40523. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  40524. var _this = this;
  40525. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  40526. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  40527. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  40528. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40529. this._depthOfFieldPostProcess.onApply = function (effect) {
  40530. effect.setTexture("depthSampler", _this._depthTexture);
  40531. effect.setTexture("grainSampler", _this._grainTexture);
  40532. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  40533. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  40534. effect.setFloat('grain_amount', _this._grainAmount);
  40535. effect.setBool('blur_noise', _this._blurNoise);
  40536. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40537. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40538. effect.setFloat('distortion', _this._distortion);
  40539. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  40540. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  40541. effect.setFloat('aperture', _this._dofAperture);
  40542. effect.setFloat('darken', _this._dofDarken);
  40543. effect.setFloat('edge_blur', _this._edgeBlur);
  40544. effect.setBool('highlights', (_this._highlightsGain !== -1));
  40545. effect.setFloat('near', _this._scene.activeCamera.minZ);
  40546. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  40547. };
  40548. };
  40549. // creates a black and white random noise texture, 512x512
  40550. LensRenderingPipeline.prototype._createGrainTexture = function () {
  40551. var size = 512;
  40552. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40553. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40554. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40555. var context = this._grainTexture.getContext();
  40556. var rand = function (min, max) {
  40557. return Math.random() * (max - min) + min;
  40558. };
  40559. var value;
  40560. for (var x = 0; x < size; x++) {
  40561. for (var y = 0; y < size; y++) {
  40562. value = Math.floor(rand(0.42, 0.58) * 255);
  40563. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  40564. context.fillRect(x, y, 1, 1);
  40565. }
  40566. }
  40567. this._grainTexture.update(false);
  40568. };
  40569. return LensRenderingPipeline;
  40570. })(BABYLON.PostProcessRenderPipeline);
  40571. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  40572. })(BABYLON || (BABYLON = {}));
  40573. //
  40574. // This post-process allows the modification of rendered colors by using
  40575. // a 'look-up table' (LUT). This effect is also called Color Grading.
  40576. //
  40577. // The object needs to be provided an url to a texture containing the color
  40578. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  40579. // Use an image editing software to tweak the LUT to match your needs.
  40580. //
  40581. // For an example of a color LUT, see here:
  40582. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  40583. // For explanations on color grading, see here:
  40584. // http://udn.epicgames.com/Three/ColorGrading.html
  40585. //
  40586. var BABYLON;
  40587. (function (BABYLON) {
  40588. var ColorCorrectionPostProcess = (function (_super) {
  40589. __extends(ColorCorrectionPostProcess, _super);
  40590. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  40591. var _this = this;
  40592. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  40593. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  40594. this._colorTableTexture.anisotropicFilteringLevel = 1;
  40595. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40596. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40597. this.onApply = function (effect) {
  40598. effect.setTexture("colorTable", _this._colorTableTexture);
  40599. };
  40600. }
  40601. return ColorCorrectionPostProcess;
  40602. })(BABYLON.PostProcess);
  40603. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  40604. })(BABYLON || (BABYLON = {}));
  40605. var BABYLON;
  40606. (function (BABYLON) {
  40607. var AnaglyphFreeCamera = (function (_super) {
  40608. __extends(AnaglyphFreeCamera, _super);
  40609. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  40610. _super.call(this, name, position, scene);
  40611. this.interaxialDistance = interaxialDistance;
  40612. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40613. }
  40614. AnaglyphFreeCamera.prototype.getTypeName = function () {
  40615. return "AnaglyphFreeCamera";
  40616. };
  40617. return AnaglyphFreeCamera;
  40618. })(BABYLON.FreeCamera);
  40619. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  40620. var AnaglyphArcRotateCamera = (function (_super) {
  40621. __extends(AnaglyphArcRotateCamera, _super);
  40622. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  40623. _super.call(this, name, alpha, beta, radius, target, scene);
  40624. this.interaxialDistance = interaxialDistance;
  40625. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40626. }
  40627. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  40628. return "AnaglyphArcRotateCamera";
  40629. };
  40630. return AnaglyphArcRotateCamera;
  40631. })(BABYLON.ArcRotateCamera);
  40632. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  40633. var AnaglyphGamepadCamera = (function (_super) {
  40634. __extends(AnaglyphGamepadCamera, _super);
  40635. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  40636. _super.call(this, name, position, scene);
  40637. this.interaxialDistance = interaxialDistance;
  40638. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40639. }
  40640. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  40641. return "AnaglyphGamepadCamera";
  40642. };
  40643. return AnaglyphGamepadCamera;
  40644. })(BABYLON.GamepadCamera);
  40645. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  40646. var AnaglyphUniversalCamera = (function (_super) {
  40647. __extends(AnaglyphUniversalCamera, _super);
  40648. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  40649. _super.call(this, name, position, scene);
  40650. this.interaxialDistance = interaxialDistance;
  40651. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40652. }
  40653. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  40654. return "AnaglyphUniversalCamera";
  40655. };
  40656. return AnaglyphUniversalCamera;
  40657. })(BABYLON.UniversalCamera);
  40658. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  40659. var StereoscopicFreeCamera = (function (_super) {
  40660. __extends(StereoscopicFreeCamera, _super);
  40661. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40662. _super.call(this, name, position, scene);
  40663. this.interaxialDistance = interaxialDistance;
  40664. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40665. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40666. }
  40667. StereoscopicFreeCamera.prototype.getTypeName = function () {
  40668. return "StereoscopicFreeCamera";
  40669. };
  40670. return StereoscopicFreeCamera;
  40671. })(BABYLON.FreeCamera);
  40672. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  40673. var StereoscopicArcRotateCamera = (function (_super) {
  40674. __extends(StereoscopicArcRotateCamera, _super);
  40675. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  40676. _super.call(this, name, alpha, beta, radius, target, scene);
  40677. this.interaxialDistance = interaxialDistance;
  40678. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40679. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40680. }
  40681. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  40682. return "StereoscopicArcRotateCamera";
  40683. };
  40684. return StereoscopicArcRotateCamera;
  40685. })(BABYLON.ArcRotateCamera);
  40686. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  40687. var StereoscopicGamepadCamera = (function (_super) {
  40688. __extends(StereoscopicGamepadCamera, _super);
  40689. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40690. _super.call(this, name, position, scene);
  40691. this.interaxialDistance = interaxialDistance;
  40692. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40693. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40694. }
  40695. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  40696. return "StereoscopicGamepadCamera";
  40697. };
  40698. return StereoscopicGamepadCamera;
  40699. })(BABYLON.GamepadCamera);
  40700. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  40701. var StereoscopicUniversalCamera = (function (_super) {
  40702. __extends(StereoscopicUniversalCamera, _super);
  40703. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40704. _super.call(this, name, position, scene);
  40705. this.interaxialDistance = interaxialDistance;
  40706. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40707. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40708. }
  40709. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  40710. return "StereoscopicUniversalCamera";
  40711. };
  40712. return StereoscopicUniversalCamera;
  40713. })(BABYLON.UniversalCamera);
  40714. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  40715. })(BABYLON || (BABYLON = {}));
  40716. var BABYLON;
  40717. (function (BABYLON) {
  40718. var HDRRenderingPipeline = (function (_super) {
  40719. __extends(HDRRenderingPipeline, _super);
  40720. /**
  40721. * @constructor
  40722. * @param {string} name - The rendering pipeline name
  40723. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40724. * @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)
  40725. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  40726. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40727. */
  40728. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  40729. var _this = this;
  40730. if (originalPostProcess === void 0) { originalPostProcess = null; }
  40731. _super.call(this, scene.getEngine(), name);
  40732. /**
  40733. * Public members
  40734. */
  40735. // Gaussian Blur
  40736. /**
  40737. * Gaussian blur coefficient
  40738. * @type {number}
  40739. */
  40740. this.gaussCoeff = 0.3;
  40741. /**
  40742. * Gaussian blur mean
  40743. * @type {number}
  40744. */
  40745. this.gaussMean = 1.0;
  40746. /**
  40747. * Gaussian blur standard deviation
  40748. * @type {number}
  40749. */
  40750. this.gaussStandDev = 0.8;
  40751. /**
  40752. * Gaussian blur multiplier. Multiplies the blur effect
  40753. * @type {number}
  40754. */
  40755. this.gaussMultiplier = 4.0;
  40756. // HDR
  40757. /**
  40758. * Exposure, controls the overall intensity of the pipeline
  40759. * @type {number}
  40760. */
  40761. this.exposure = 1.0;
  40762. /**
  40763. * Minimum luminance that the post-process can output. Luminance is >= 0
  40764. * @type {number}
  40765. */
  40766. this.minimumLuminance = 1.0;
  40767. /**
  40768. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  40769. * @type {number}
  40770. */
  40771. this.maximumLuminance = 1e20;
  40772. /**
  40773. * Increase rate for luminance: eye adaptation speed to dark
  40774. * @type {number}
  40775. */
  40776. this.luminanceIncreaserate = 0.5;
  40777. /**
  40778. * Decrease rate for luminance: eye adaptation speed to bright
  40779. * @type {number}
  40780. */
  40781. this.luminanceDecreaseRate = 0.5;
  40782. // Bright pass
  40783. /**
  40784. * Minimum luminance needed to compute HDR
  40785. * @type {number}
  40786. */
  40787. this.brightThreshold = 0.8;
  40788. this._needUpdate = true;
  40789. this._scene = scene;
  40790. // Bright pass
  40791. this._createBrightPassPostProcess(scene, ratio);
  40792. // Down sample X4
  40793. this._createDownSampleX4PostProcess(scene, ratio);
  40794. // Create gaussian blur post-processes
  40795. this._createGaussianBlurPostProcess(scene, ratio);
  40796. // Texture adder
  40797. this._createTextureAdderPostProcess(scene, ratio);
  40798. // Luminance generator
  40799. this._createLuminanceGeneratorPostProcess(scene);
  40800. // HDR
  40801. this._createHDRPostProcess(scene, ratio);
  40802. // Pass postprocess
  40803. if (originalPostProcess === null) {
  40804. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40805. }
  40806. else {
  40807. this._originalPostProcess = originalPostProcess;
  40808. }
  40809. // Configure pipeline
  40810. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  40811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  40812. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  40813. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  40814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  40815. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  40816. var addDownSamplerPostProcess = function (id) {
  40817. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  40818. };
  40819. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40820. addDownSamplerPostProcess(i);
  40821. }
  40822. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  40823. // Finish
  40824. scene.postProcessRenderPipelineManager.addPipeline(this);
  40825. if (cameras !== null) {
  40826. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40827. }
  40828. this.update();
  40829. }
  40830. /**
  40831. * Tells the pipeline to update its post-processes
  40832. */
  40833. HDRRenderingPipeline.prototype.update = function () {
  40834. this._needUpdate = true;
  40835. };
  40836. /**
  40837. * Returns the current calculated luminance
  40838. */
  40839. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  40840. return this._hdrCurrentLuminance;
  40841. };
  40842. /**
  40843. * Returns the currently drawn luminance
  40844. */
  40845. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  40846. return this._hdrOutputLuminance;
  40847. };
  40848. /**
  40849. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  40850. */
  40851. HDRRenderingPipeline.prototype.dispose = function () {
  40852. this._originalPostProcess = undefined;
  40853. this._brightPassPostProcess = undefined;
  40854. this._downSampleX4PostProcess = undefined;
  40855. this._guassianBlurHPostProcess = undefined;
  40856. this._guassianBlurVPostProcess = undefined;
  40857. this._textureAdderPostProcess = undefined;
  40858. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40859. this._downSamplePostProcesses[i] = undefined;
  40860. }
  40861. this._hdrPostProcess = undefined;
  40862. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40863. };
  40864. /**
  40865. * Creates the HDR post-process and computes the luminance adaptation
  40866. */
  40867. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  40868. var _this = this;
  40869. var hdrLastLuminance = 0.0;
  40870. this._hdrOutputLuminance = -1.0;
  40871. this._hdrCurrentLuminance = 1.0;
  40872. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  40873. this._hdrPostProcess.onApply = function (effect) {
  40874. if (_this._hdrOutputLuminance < 0.0) {
  40875. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40876. }
  40877. else {
  40878. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  40879. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  40880. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  40881. }
  40882. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  40883. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  40884. }
  40885. else {
  40886. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40887. }
  40888. }
  40889. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  40890. hdrLastLuminance += scene.getEngine().getDeltaTime();
  40891. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40892. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40893. effect.setFloat("exposure", _this.exposure);
  40894. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  40895. _this._needUpdate = false;
  40896. };
  40897. };
  40898. /**
  40899. * Texture Adder post-process
  40900. */
  40901. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  40902. var _this = this;
  40903. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  40904. this._textureAdderPostProcess.onApply = function (effect) {
  40905. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40906. };
  40907. };
  40908. /**
  40909. * Down sample X4 post-process
  40910. */
  40911. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  40912. var _this = this;
  40913. var downSampleX4Offsets = new Array(32);
  40914. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  40915. this._downSampleX4PostProcess.onApply = function (effect) {
  40916. if (_this._needUpdate) {
  40917. var id = 0;
  40918. for (var i = -2; i < 2; i++) {
  40919. for (var j = -2; j < 2; j++) {
  40920. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  40921. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  40922. id += 2;
  40923. }
  40924. }
  40925. }
  40926. effect.setArray2("dsOffsets", downSampleX4Offsets);
  40927. };
  40928. };
  40929. /**
  40930. * Bright pass post-process
  40931. */
  40932. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  40933. var _this = this;
  40934. var brightOffsets = new Array(8);
  40935. var brightPassCallback = function (effect) {
  40936. if (_this._needUpdate) {
  40937. var sU = (1.0 / _this._brightPassPostProcess.width);
  40938. var sV = (1.0 / _this._brightPassPostProcess.height);
  40939. brightOffsets[0] = -0.5 * sU;
  40940. brightOffsets[1] = 0.5 * sV;
  40941. brightOffsets[2] = 0.5 * sU;
  40942. brightOffsets[3] = 0.5 * sV;
  40943. brightOffsets[4] = -0.5 * sU;
  40944. brightOffsets[5] = -0.5 * sV;
  40945. brightOffsets[6] = 0.5 * sU;
  40946. brightOffsets[7] = -0.5 * sV;
  40947. }
  40948. effect.setArray2("dsOffsets", brightOffsets);
  40949. effect.setFloat("brightThreshold", _this.brightThreshold);
  40950. };
  40951. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  40952. this._brightPassPostProcess.onApply = brightPassCallback;
  40953. };
  40954. /**
  40955. * Luminance generator. Creates the luminance post-process and down sample post-processes
  40956. */
  40957. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  40958. var _this = this;
  40959. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  40960. var luminanceOffsets = new Array(8);
  40961. var downSampleOffsets = new Array(18);
  40962. var halfDestPixelSize;
  40963. this._downSamplePostProcesses = new Array(lumSteps);
  40964. // Utils for luminance
  40965. var luminanceUpdateSourceOffsets = function (width, height) {
  40966. var sU = (1.0 / width);
  40967. var sV = (1.0 / height);
  40968. luminanceOffsets[0] = -0.5 * sU;
  40969. luminanceOffsets[1] = 0.5 * sV;
  40970. luminanceOffsets[2] = 0.5 * sU;
  40971. luminanceOffsets[3] = 0.5 * sV;
  40972. luminanceOffsets[4] = -0.5 * sU;
  40973. luminanceOffsets[5] = -0.5 * sV;
  40974. luminanceOffsets[6] = 0.5 * sU;
  40975. luminanceOffsets[7] = -0.5 * sV;
  40976. };
  40977. var luminanceUpdateDestOffsets = function (width, height) {
  40978. var id = 0;
  40979. for (var x = -1; x < 2; x++) {
  40980. for (var y = -1; y < 2; y++) {
  40981. downSampleOffsets[id] = (x) / width;
  40982. downSampleOffsets[id + 1] = (y) / height;
  40983. id += 2;
  40984. }
  40985. }
  40986. };
  40987. // Luminance callback
  40988. var luminanceCallback = function (effect) {
  40989. if (_this._needUpdate) {
  40990. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  40991. }
  40992. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40993. effect.setArray2("lumOffsets", luminanceOffsets);
  40994. };
  40995. // Down sample callbacks
  40996. var downSampleCallback = function (indice) {
  40997. var i = indice;
  40998. return function (effect) {
  40999. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  41000. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  41001. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  41002. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  41003. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  41004. effect.setArray2("dsOffsets", downSampleOffsets);
  41005. };
  41006. };
  41007. var downSampleAfterRenderCallback = function (effect) {
  41008. // Unpack result
  41009. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  41010. 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);
  41011. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  41012. };
  41013. // Create luminance post-process
  41014. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  41015. 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);
  41016. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  41017. // Create down sample post-processes
  41018. for (var i = lumSteps - 2; i >= 0; i--) {
  41019. var length = Math.pow(3, i);
  41020. ratio = { width: length, height: length };
  41021. var defines = "#define DOWN_SAMPLE\n";
  41022. if (i === 0) {
  41023. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  41024. }
  41025. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  41026. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  41027. if (i === 0) {
  41028. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  41029. }
  41030. }
  41031. };
  41032. /**
  41033. * Gaussian blur post-processes. Horizontal and Vertical
  41034. */
  41035. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  41036. var _this = this;
  41037. var blurOffsetsW = new Array(9);
  41038. var blurOffsetsH = new Array(9);
  41039. var blurWeights = new Array(9);
  41040. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  41041. // Utils for gaussian blur
  41042. var calculateBlurOffsets = function (height) {
  41043. var lastOutputDimensions = {
  41044. width: scene.getEngine().getRenderWidth(),
  41045. height: scene.getEngine().getRenderHeight()
  41046. };
  41047. for (var i = 0; i < 9; i++) {
  41048. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  41049. if (height) {
  41050. blurOffsetsH[i] = value;
  41051. }
  41052. else {
  41053. blurOffsetsW[i] = value;
  41054. }
  41055. }
  41056. };
  41057. var calculateWeights = function () {
  41058. var x = 0.0;
  41059. for (var i = 0; i < 9; i++) {
  41060. x = (i - 4.0) / 4.0;
  41061. 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));
  41062. }
  41063. };
  41064. // Callback
  41065. var gaussianBlurCallback = function (height) {
  41066. return function (effect) {
  41067. if (_this._needUpdate) {
  41068. calculateWeights();
  41069. calculateBlurOffsets(height);
  41070. }
  41071. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  41072. effect.setArray("blurWeights", blurWeights);
  41073. effect.setFloat("multiplier", _this.gaussMultiplier);
  41074. };
  41075. };
  41076. // Create horizontal gaussian blur post-processes
  41077. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  41078. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  41079. // Create vertical gaussian blur post-process
  41080. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  41081. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  41082. };
  41083. // Luminance generator
  41084. HDRRenderingPipeline.LUM_STEPS = 6;
  41085. return HDRRenderingPipeline;
  41086. })(BABYLON.PostProcessRenderPipeline);
  41087. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  41088. })(BABYLON || (BABYLON = {}));
  41089. var BABYLON;
  41090. (function (BABYLON) {
  41091. var FaceAdjacencies = (function () {
  41092. function FaceAdjacencies() {
  41093. this.edges = new Array();
  41094. this.edgesConnectedCount = 0;
  41095. }
  41096. return FaceAdjacencies;
  41097. })();
  41098. var EdgesRenderer = (function () {
  41099. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  41100. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  41101. if (epsilon === void 0) { epsilon = 0.95; }
  41102. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  41103. this.edgesWidthScalerForOrthographic = 1000.0;
  41104. this.edgesWidthScalerForPerspective = 50.0;
  41105. this._linesPositions = new Array();
  41106. this._linesNormals = new Array();
  41107. this._linesIndices = new Array();
  41108. this._buffers = new Array();
  41109. this._checkVerticesInsteadOfIndices = false;
  41110. this._source = source;
  41111. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  41112. this._epsilon = epsilon;
  41113. this._prepareRessources();
  41114. this._generateEdgesLines();
  41115. }
  41116. EdgesRenderer.prototype._prepareRessources = function () {
  41117. if (this._lineShader) {
  41118. return;
  41119. }
  41120. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  41121. attributes: ["position", "normal"],
  41122. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  41123. });
  41124. this._lineShader.disableDepthWrite = true;
  41125. this._lineShader.backFaceCulling = false;
  41126. };
  41127. EdgesRenderer.prototype.dispose = function () {
  41128. this._vb0.dispose();
  41129. this._vb1.dispose();
  41130. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  41131. this._lineShader.dispose();
  41132. };
  41133. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  41134. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  41135. return 0;
  41136. }
  41137. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  41138. return 1;
  41139. }
  41140. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  41141. return 2;
  41142. }
  41143. return -1;
  41144. };
  41145. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  41146. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  41147. return 0;
  41148. }
  41149. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  41150. return 1;
  41151. }
  41152. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  41153. return 2;
  41154. }
  41155. return -1;
  41156. };
  41157. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  41158. var needToCreateLine;
  41159. if (edge === undefined) {
  41160. needToCreateLine = true;
  41161. }
  41162. else {
  41163. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  41164. needToCreateLine = dotProduct < this._epsilon;
  41165. }
  41166. if (needToCreateLine) {
  41167. var offset = this._linesPositions.length / 3;
  41168. var normal = p0.subtract(p1);
  41169. normal.normalize();
  41170. // Positions
  41171. this._linesPositions.push(p0.x);
  41172. this._linesPositions.push(p0.y);
  41173. this._linesPositions.push(p0.z);
  41174. this._linesPositions.push(p0.x);
  41175. this._linesPositions.push(p0.y);
  41176. this._linesPositions.push(p0.z);
  41177. this._linesPositions.push(p1.x);
  41178. this._linesPositions.push(p1.y);
  41179. this._linesPositions.push(p1.z);
  41180. this._linesPositions.push(p1.x);
  41181. this._linesPositions.push(p1.y);
  41182. this._linesPositions.push(p1.z);
  41183. // Normals
  41184. this._linesNormals.push(p1.x);
  41185. this._linesNormals.push(p1.y);
  41186. this._linesNormals.push(p1.z);
  41187. this._linesNormals.push(-1);
  41188. this._linesNormals.push(p1.x);
  41189. this._linesNormals.push(p1.y);
  41190. this._linesNormals.push(p1.z);
  41191. this._linesNormals.push(1);
  41192. this._linesNormals.push(p0.x);
  41193. this._linesNormals.push(p0.y);
  41194. this._linesNormals.push(p0.z);
  41195. this._linesNormals.push(-1);
  41196. this._linesNormals.push(p0.x);
  41197. this._linesNormals.push(p0.y);
  41198. this._linesNormals.push(p0.z);
  41199. this._linesNormals.push(1);
  41200. // Indices
  41201. this._linesIndices.push(offset);
  41202. this._linesIndices.push(offset + 1);
  41203. this._linesIndices.push(offset + 2);
  41204. this._linesIndices.push(offset);
  41205. this._linesIndices.push(offset + 2);
  41206. this._linesIndices.push(offset + 3);
  41207. }
  41208. };
  41209. EdgesRenderer.prototype._generateEdgesLines = function () {
  41210. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41211. var indices = this._source.getIndices();
  41212. // First let's find adjacencies
  41213. var adjacencies = new Array();
  41214. var faceNormals = new Array();
  41215. var index;
  41216. var faceAdjacencies;
  41217. // Prepare faces
  41218. for (index = 0; index < indices.length; index += 3) {
  41219. faceAdjacencies = new FaceAdjacencies();
  41220. var p0Index = indices[index];
  41221. var p1Index = indices[index + 1];
  41222. var p2Index = indices[index + 2];
  41223. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  41224. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  41225. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  41226. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  41227. faceNormal.normalize();
  41228. faceNormals.push(faceNormal);
  41229. adjacencies.push(faceAdjacencies);
  41230. }
  41231. // Scan
  41232. for (index = 0; index < adjacencies.length; index++) {
  41233. faceAdjacencies = adjacencies[index];
  41234. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  41235. var otherFaceAdjacencies = adjacencies[otherIndex];
  41236. if (faceAdjacencies.edgesConnectedCount === 3) {
  41237. break;
  41238. }
  41239. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  41240. continue;
  41241. }
  41242. var otherP0 = indices[otherIndex * 3];
  41243. var otherP1 = indices[otherIndex * 3 + 1];
  41244. var otherP2 = indices[otherIndex * 3 + 2];
  41245. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  41246. var otherEdgeIndex;
  41247. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  41248. continue;
  41249. }
  41250. switch (edgeIndex) {
  41251. case 0:
  41252. if (this._checkVerticesInsteadOfIndices) {
  41253. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41254. }
  41255. else {
  41256. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  41257. }
  41258. break;
  41259. case 1:
  41260. if (this._checkVerticesInsteadOfIndices) {
  41261. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41262. }
  41263. else {
  41264. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  41265. }
  41266. break;
  41267. case 2:
  41268. if (this._checkVerticesInsteadOfIndices) {
  41269. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41270. }
  41271. else {
  41272. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  41273. }
  41274. break;
  41275. }
  41276. if (otherEdgeIndex === -1) {
  41277. continue;
  41278. }
  41279. faceAdjacencies.edges[edgeIndex] = otherIndex;
  41280. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  41281. faceAdjacencies.edgesConnectedCount++;
  41282. otherFaceAdjacencies.edgesConnectedCount++;
  41283. if (faceAdjacencies.edgesConnectedCount === 3) {
  41284. break;
  41285. }
  41286. }
  41287. }
  41288. }
  41289. // Create lines
  41290. for (index = 0; index < adjacencies.length; index++) {
  41291. // 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
  41292. var current = adjacencies[index];
  41293. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  41294. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  41295. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  41296. }
  41297. // Merge into a single mesh
  41298. var engine = this._source.getScene().getEngine();
  41299. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  41300. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  41301. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  41302. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  41303. this._ib = engine.createIndexBuffer(this._linesIndices);
  41304. this._indicesCount = this._linesIndices.length;
  41305. };
  41306. EdgesRenderer.prototype.render = function () {
  41307. if (!this._lineShader.isReady()) {
  41308. return;
  41309. }
  41310. var scene = this._source.getScene();
  41311. var engine = scene.getEngine();
  41312. this._lineShader._preBind();
  41313. // VBOs
  41314. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  41315. scene.resetCachedMaterial();
  41316. this._lineShader.setColor4("color", this._source.edgesColor);
  41317. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  41318. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  41319. }
  41320. else {
  41321. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  41322. }
  41323. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  41324. this._lineShader.bind(this._source.getWorldMatrix());
  41325. // Draw order
  41326. engine.draw(true, 0, this._indicesCount);
  41327. this._lineShader.unbind();
  41328. engine.setDepthWrite(true);
  41329. };
  41330. return EdgesRenderer;
  41331. })();
  41332. BABYLON.EdgesRenderer = EdgesRenderer;
  41333. })(BABYLON || (BABYLON = {}));
  41334. var BABYLON;
  41335. (function (BABYLON) {
  41336. (function (TonemappingOperator) {
  41337. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  41338. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  41339. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  41340. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  41341. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  41342. var TonemappingOperator = BABYLON.TonemappingOperator;
  41343. ;
  41344. var TonemapPostProcess = (function (_super) {
  41345. __extends(TonemapPostProcess, _super);
  41346. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  41347. var _this = this;
  41348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41349. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41350. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  41351. this._operator = _operator;
  41352. this.exposureAdjustment = exposureAdjustment;
  41353. var defines = "#define ";
  41354. if (this._operator === TonemappingOperator.Hable)
  41355. defines += "HABLE_TONEMAPPING";
  41356. else if (this._operator === TonemappingOperator.Reinhard)
  41357. defines += "REINHARD_TONEMAPPING";
  41358. else if (this._operator === TonemappingOperator.HejiDawson)
  41359. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  41360. else if (this._operator === TonemappingOperator.Photographic)
  41361. defines += "PHOTOGRAPHIC_TONEMAPPING";
  41362. //sadly a second call to create the effect.
  41363. this.updateEffect(defines);
  41364. this.onApply = function (effect) {
  41365. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  41366. };
  41367. }
  41368. return TonemapPostProcess;
  41369. })(BABYLON.PostProcess);
  41370. BABYLON.TonemapPostProcess = TonemapPostProcess;
  41371. })(BABYLON || (BABYLON = {}));
  41372. var BABYLON;
  41373. (function (BABYLON) {
  41374. var ReflectionProbe = (function () {
  41375. function ReflectionProbe(name, size, scene, generateMipMaps) {
  41376. var _this = this;
  41377. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41378. this.name = name;
  41379. this._viewMatrix = BABYLON.Matrix.Identity();
  41380. this._target = BABYLON.Vector3.Zero();
  41381. this._add = BABYLON.Vector3.Zero();
  41382. this.invertYAxis = false;
  41383. this.position = BABYLON.Vector3.Zero();
  41384. this._scene = scene;
  41385. this._scene.reflectionProbes.push(this);
  41386. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  41387. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  41388. switch (faceIndex) {
  41389. case 0:
  41390. _this._add.copyFromFloats(1, 0, 0);
  41391. break;
  41392. case 1:
  41393. _this._add.copyFromFloats(-1, 0, 0);
  41394. break;
  41395. case 2:
  41396. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  41397. break;
  41398. case 3:
  41399. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  41400. break;
  41401. case 4:
  41402. _this._add.copyFromFloats(0, 0, 1);
  41403. break;
  41404. case 5:
  41405. _this._add.copyFromFloats(0, 0, -1);
  41406. break;
  41407. }
  41408. if (_this._attachedMesh) {
  41409. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  41410. }
  41411. _this.position.addToRef(_this._add, _this._target);
  41412. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  41413. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  41414. };
  41415. this._renderTargetTexture.onAfterUnbind = function () {
  41416. scene.updateTransformMatrix(true);
  41417. };
  41418. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41419. }
  41420. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  41421. get: function () {
  41422. return this._renderTargetTexture.refreshRate;
  41423. },
  41424. set: function (value) {
  41425. this._renderTargetTexture.refreshRate = value;
  41426. },
  41427. enumerable: true,
  41428. configurable: true
  41429. });
  41430. ReflectionProbe.prototype.getScene = function () {
  41431. return this._scene;
  41432. };
  41433. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  41434. get: function () {
  41435. return this._renderTargetTexture;
  41436. },
  41437. enumerable: true,
  41438. configurable: true
  41439. });
  41440. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  41441. get: function () {
  41442. return this._renderTargetTexture.renderList;
  41443. },
  41444. enumerable: true,
  41445. configurable: true
  41446. });
  41447. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  41448. this._attachedMesh = mesh;
  41449. };
  41450. ReflectionProbe.prototype.dispose = function () {
  41451. var index = this._scene.reflectionProbes.indexOf(this);
  41452. if (index !== -1) {
  41453. // Remove from the scene if found
  41454. this._scene.reflectionProbes.splice(index, 1);
  41455. }
  41456. if (this._renderTargetTexture) {
  41457. this._renderTargetTexture.dispose();
  41458. this._renderTargetTexture = null;
  41459. }
  41460. };
  41461. return ReflectionProbe;
  41462. })();
  41463. BABYLON.ReflectionProbe = ReflectionProbe;
  41464. })(BABYLON || (BABYLON = {}));
  41465. var BABYLON;
  41466. (function (BABYLON) {
  41467. var SolidParticle = (function () {
  41468. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  41469. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  41470. this.position = BABYLON.Vector3.Zero(); // position
  41471. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41472. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  41473. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  41474. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41475. this.alive = true; // alive
  41476. this.idx = particleIndex;
  41477. this._pos = positionIndex;
  41478. this._model = model;
  41479. this.shapeId = shapeId;
  41480. this.idxInShape = idxInShape;
  41481. }
  41482. Object.defineProperty(SolidParticle.prototype, "scale", {
  41483. //legacy support, changed scale to scaling
  41484. get: function () {
  41485. return this.scaling;
  41486. },
  41487. set: function (scale) {
  41488. this.scaling = scale;
  41489. },
  41490. enumerable: true,
  41491. configurable: true
  41492. });
  41493. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41494. //legacy support, changed quaternion to rotationQuaternion
  41495. get: function () {
  41496. return this.rotationQuaternion;
  41497. },
  41498. set: function (q) {
  41499. this.rotationQuaternion = q;
  41500. },
  41501. enumerable: true,
  41502. configurable: true
  41503. });
  41504. return SolidParticle;
  41505. })();
  41506. BABYLON.SolidParticle = SolidParticle;
  41507. var ModelShape = (function () {
  41508. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41509. this.shapeID = id;
  41510. this._shape = shape;
  41511. this._shapeUV = shapeUV;
  41512. this._positionFunction = posFunction;
  41513. this._vertexFunction = vtxFunction;
  41514. }
  41515. return ModelShape;
  41516. })();
  41517. BABYLON.ModelShape = ModelShape;
  41518. })(BABYLON || (BABYLON = {}));
  41519. var BABYLON;
  41520. (function (BABYLON) {
  41521. /**
  41522. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  41523. */
  41524. var SolidParticleSystem = (function () {
  41525. /**
  41526. * Creates a SPS (Solid Particle System) object.
  41527. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41528. * `scene` (Scene) is the scene in which the SPS is added.
  41529. * `updatableè (default true) : if the SPS must be updatable or immutable.
  41530. * `isPickable` (default false) : if the solid particles must be pickable.
  41531. */
  41532. function SolidParticleSystem(name, scene, options) {
  41533. // public members
  41534. /**
  41535. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41536. * Example : var p = SPS.particles[i];
  41537. */
  41538. this.particles = new Array();
  41539. /**
  41540. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41541. */
  41542. this.nbParticles = 0;
  41543. /**
  41544. * If the particles must ever face the camera (default false). Useful for planar particles.
  41545. */
  41546. this.billboard = false;
  41547. /**
  41548. * This a counter ofr your own usage. It's not set by any SPS functions.
  41549. */
  41550. this.counter = 0;
  41551. /**
  41552. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41553. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  41554. */
  41555. this.vars = {};
  41556. this._positions = new Array();
  41557. this._indices = new Array();
  41558. this._normals = new Array();
  41559. this._colors = new Array();
  41560. this._uvs = new Array();
  41561. this._index = 0; // indices index
  41562. this._updatable = true;
  41563. this._pickable = false;
  41564. this._isVisibilityBoxLocked = false;
  41565. this._alwaysVisible = false;
  41566. this._shapeCounter = 0;
  41567. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  41568. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41569. this._computeParticleColor = true;
  41570. this._computeParticleTexture = true;
  41571. this._computeParticleRotation = true;
  41572. this._computeParticleVertex = false;
  41573. this._computeBoundingBox = false;
  41574. this._cam_axisZ = BABYLON.Vector3.Zero();
  41575. this._cam_axisY = BABYLON.Vector3.Zero();
  41576. this._cam_axisX = BABYLON.Vector3.Zero();
  41577. this._axisX = BABYLON.Axis.X;
  41578. this._axisY = BABYLON.Axis.Y;
  41579. this._axisZ = BABYLON.Axis.Z;
  41580. this._fakeCamPos = BABYLON.Vector3.Zero();
  41581. this._rotMatrix = new BABYLON.Matrix();
  41582. this._invertMatrix = new BABYLON.Matrix();
  41583. this._rotated = BABYLON.Vector3.Zero();
  41584. this._quaternion = new BABYLON.Quaternion();
  41585. this._vertex = BABYLON.Vector3.Zero();
  41586. this._normal = BABYLON.Vector3.Zero();
  41587. this._yaw = 0.0;
  41588. this._pitch = 0.0;
  41589. this._roll = 0.0;
  41590. this._halfroll = 0.0;
  41591. this._halfpitch = 0.0;
  41592. this._halfyaw = 0.0;
  41593. this._sinRoll = 0.0;
  41594. this._cosRoll = 0.0;
  41595. this._sinPitch = 0.0;
  41596. this._cosPitch = 0.0;
  41597. this._sinYaw = 0.0;
  41598. this._cosYaw = 0.0;
  41599. this._w = 0.0;
  41600. this._minimum = BABYLON.Tmp.Vector3[0];
  41601. this._maximum = BABYLON.Tmp.Vector3[1];
  41602. this.name = name;
  41603. this._scene = scene;
  41604. this._camera = scene.activeCamera;
  41605. this._pickable = options ? options.isPickable : false;
  41606. if (options && options.updatable) {
  41607. this._updatable = options.updatable;
  41608. }
  41609. else {
  41610. this._updatable = true;
  41611. }
  41612. if (this._pickable) {
  41613. this.pickedParticles = [];
  41614. }
  41615. }
  41616. /**
  41617. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41618. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41619. */
  41620. SolidParticleSystem.prototype.buildMesh = function () {
  41621. if (this.nbParticles === 0) {
  41622. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41623. this.addShape(triangle, 1);
  41624. triangle.dispose();
  41625. }
  41626. this._positions32 = new Float32Array(this._positions);
  41627. this._uvs32 = new Float32Array(this._uvs);
  41628. this._colors32 = new Float32Array(this._colors);
  41629. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41630. this._normals32 = new Float32Array(this._normals);
  41631. this._fixedNormal32 = new Float32Array(this._normals);
  41632. var vertexData = new BABYLON.VertexData();
  41633. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41634. vertexData.indices = this._indices;
  41635. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41636. if (this._uvs32) {
  41637. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41638. ;
  41639. }
  41640. if (this._colors32) {
  41641. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41642. }
  41643. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41644. vertexData.applyToMesh(mesh, this._updatable);
  41645. this.mesh = mesh;
  41646. this.mesh.isPickable = this._pickable;
  41647. // free memory
  41648. this._positions = null;
  41649. this._normals = null;
  41650. this._uvs = null;
  41651. this._colors = null;
  41652. if (!this._updatable) {
  41653. this.particles.length = 0;
  41654. }
  41655. return mesh;
  41656. };
  41657. /**
  41658. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41659. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41660. * Thus the particles generated from `digest()` have their property `position` set yet.
  41661. * `mesh` (`Mesh`) is the mesh to be digested
  41662. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41663. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41664. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41665. */
  41666. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41667. var size = (options && options.facetNb) || 1;
  41668. var number = (options && options.number);
  41669. var delta = (options && options.delta) || 0;
  41670. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41671. var meshInd = mesh.getIndices();
  41672. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41673. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41674. var f = 0; // facet counter
  41675. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41676. // compute size from number
  41677. if (number) {
  41678. number = (number > totalFacets) ? totalFacets : number;
  41679. size = Math.round(totalFacets / number);
  41680. delta = 0;
  41681. }
  41682. else {
  41683. size = (size > totalFacets) ? totalFacets : size;
  41684. }
  41685. var facetPos = []; // submesh positions
  41686. var facetInd = []; // submesh indices
  41687. var facetUV = []; // submesh UV
  41688. var facetCol = []; // submesh colors
  41689. var barycenter = BABYLON.Tmp.Vector3[0];
  41690. var rand;
  41691. var sizeO = size;
  41692. while (f < totalFacets) {
  41693. size = sizeO + Math.floor((1 + delta) * Math.random());
  41694. if (f > totalFacets - size) {
  41695. size = totalFacets - f;
  41696. }
  41697. // reset temp arrays
  41698. facetPos.length = 0;
  41699. facetInd.length = 0;
  41700. facetUV.length = 0;
  41701. facetCol.length = 0;
  41702. // iterate over "size" facets
  41703. var fi = 0;
  41704. for (var j = f * 3; j < (f + size) * 3; j++) {
  41705. facetInd.push(fi);
  41706. var i = meshInd[j];
  41707. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41708. if (meshUV) {
  41709. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41710. }
  41711. if (meshCol) {
  41712. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41713. }
  41714. fi++;
  41715. }
  41716. // create a model shape for each single particle
  41717. var idx = this.nbParticles;
  41718. var shape = this._posToShape(facetPos);
  41719. var shapeUV = this._uvsToShapeUV(facetUV);
  41720. // compute the barycenter of the shape
  41721. var v;
  41722. for (v = 0; v < shape.length; v++) {
  41723. barycenter.addInPlace(shape[v]);
  41724. }
  41725. barycenter.scaleInPlace(1 / shape.length);
  41726. // shift the shape from its barycenter to the origin
  41727. for (v = 0; v < shape.length; v++) {
  41728. shape[v].subtractInPlace(barycenter);
  41729. }
  41730. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41731. // add the particle in the SPS
  41732. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  41733. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  41734. // initialize the particle position
  41735. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41736. this._index += shape.length;
  41737. idx++;
  41738. this.nbParticles++;
  41739. this._shapeCounter++;
  41740. f += size;
  41741. }
  41742. return this;
  41743. };
  41744. //reset copy
  41745. SolidParticleSystem.prototype._resetCopy = function () {
  41746. this._copy.position.x = 0;
  41747. this._copy.position.y = 0;
  41748. this._copy.position.z = 0;
  41749. this._copy.rotation.x = 0;
  41750. this._copy.rotation.y = 0;
  41751. this._copy.rotation.z = 0;
  41752. this._copy.rotationQuaternion = null;
  41753. this._copy.scaling.x = 1;
  41754. this._copy.scaling.y = 1;
  41755. this._copy.scaling.z = 1;
  41756. this._copy.uvs.x = 0;
  41757. this._copy.uvs.y = 0;
  41758. this._copy.uvs.z = 1;
  41759. this._copy.uvs.w = 1;
  41760. this._copy.color = null;
  41761. };
  41762. // _meshBuilder : inserts the shape model in the global SPS mesh
  41763. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  41764. var i;
  41765. var u = 0;
  41766. var c = 0;
  41767. this._resetCopy();
  41768. if (options && options.positionFunction) {
  41769. options.positionFunction(this._copy, idx, idxInShape);
  41770. }
  41771. if (this._copy.rotationQuaternion) {
  41772. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41773. }
  41774. else {
  41775. this._yaw = this._copy.rotation.y;
  41776. this._pitch = this._copy.rotation.x;
  41777. this._roll = this._copy.rotation.z;
  41778. this._quaternionRotationYPR();
  41779. }
  41780. this._quaternionToRotationMatrix();
  41781. for (i = 0; i < shape.length; i++) {
  41782. this._vertex.x = shape[i].x;
  41783. this._vertex.y = shape[i].y;
  41784. this._vertex.z = shape[i].z;
  41785. if (options && options.vertexFunction) {
  41786. options.vertexFunction(this._copy, this._vertex, i);
  41787. }
  41788. this._vertex.x *= this._copy.scaling.x;
  41789. this._vertex.y *= this._copy.scaling.y;
  41790. this._vertex.z *= this._copy.scaling.z;
  41791. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41792. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41793. if (meshUV) {
  41794. 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);
  41795. u += 2;
  41796. }
  41797. if (this._copy.color) {
  41798. this._color = this._copy.color;
  41799. }
  41800. else if (meshCol && meshCol[c]) {
  41801. this._color.r = meshCol[c];
  41802. this._color.g = meshCol[c + 1];
  41803. this._color.b = meshCol[c + 2];
  41804. this._color.a = meshCol[c + 3];
  41805. }
  41806. else {
  41807. this._color.r = 1;
  41808. this._color.g = 1;
  41809. this._color.b = 1;
  41810. this._color.a = 1;
  41811. }
  41812. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41813. c += 4;
  41814. }
  41815. for (i = 0; i < meshInd.length; i++) {
  41816. indices.push(p + meshInd[i]);
  41817. }
  41818. if (this._pickable) {
  41819. var nbfaces = meshInd.length / 3;
  41820. for (i = 0; i < nbfaces; i++) {
  41821. this.pickedParticles.push({ idx: idx, faceId: i });
  41822. }
  41823. }
  41824. };
  41825. // returns a shape array from positions array
  41826. SolidParticleSystem.prototype._posToShape = function (positions) {
  41827. var shape = [];
  41828. for (var i = 0; i < positions.length; i += 3) {
  41829. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41830. }
  41831. return shape;
  41832. };
  41833. // returns a shapeUV array from a Vector4 uvs
  41834. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41835. var shapeUV = [];
  41836. if (uvs) {
  41837. for (var i = 0; i < uvs.length; i++)
  41838. shapeUV.push(uvs[i]);
  41839. }
  41840. return shapeUV;
  41841. };
  41842. // adds a new particle object in the particles array
  41843. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  41844. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  41845. };
  41846. /**
  41847. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41848. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  41849. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  41850. * `nb` (positive integer) the number of particles to be created from this model
  41851. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41852. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41853. */
  41854. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41855. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41856. var meshInd = mesh.getIndices();
  41857. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41858. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41859. var shape = this._posToShape(meshPos);
  41860. var shapeUV = this._uvsToShapeUV(meshUV);
  41861. var posfunc = options ? options.positionFunction : null;
  41862. var vtxfunc = options ? options.vertexFunction : null;
  41863. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41864. // particles
  41865. var idx = this.nbParticles;
  41866. for (var i = 0; i < nb; i++) {
  41867. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  41868. if (this._updatable) {
  41869. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  41870. }
  41871. this._index += shape.length;
  41872. idx++;
  41873. }
  41874. this.nbParticles += nb;
  41875. this._shapeCounter++;
  41876. return this._shapeCounter - 1;
  41877. };
  41878. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41879. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41880. this._resetCopy();
  41881. if (particle._model._positionFunction) {
  41882. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41883. }
  41884. if (this._copy.rotationQuaternion) {
  41885. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41886. }
  41887. else {
  41888. this._yaw = this._copy.rotation.y;
  41889. this._pitch = this._copy.rotation.x;
  41890. this._roll = this._copy.rotation.z;
  41891. this._quaternionRotationYPR();
  41892. }
  41893. this._quaternionToRotationMatrix();
  41894. this._shape = particle._model._shape;
  41895. for (var pt = 0; pt < this._shape.length; pt++) {
  41896. this._vertex.x = this._shape[pt].x;
  41897. this._vertex.y = this._shape[pt].y;
  41898. this._vertex.z = this._shape[pt].z;
  41899. if (particle._model._vertexFunction) {
  41900. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41901. }
  41902. this._vertex.x *= this._copy.scaling.x;
  41903. this._vertex.y *= this._copy.scaling.y;
  41904. this._vertex.z *= this._copy.scaling.z;
  41905. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41906. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41907. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41908. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41909. }
  41910. particle.position.x = 0;
  41911. particle.position.y = 0;
  41912. particle.position.z = 0;
  41913. particle.rotation.x = 0;
  41914. particle.rotation.y = 0;
  41915. particle.rotation.z = 0;
  41916. particle.rotationQuaternion = null;
  41917. particle.scaling.x = 1;
  41918. particle.scaling.y = 1;
  41919. particle.scaling.z = 1;
  41920. };
  41921. /**
  41922. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41923. */
  41924. SolidParticleSystem.prototype.rebuildMesh = function () {
  41925. for (var p = 0; p < this.particles.length; p++) {
  41926. this._rebuildParticle(this.particles[p]);
  41927. }
  41928. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41929. };
  41930. /**
  41931. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41932. * This method calls `updateParticle()` for each particle of the SPS.
  41933. * For an animated SPS, it is usually called within the render loop.
  41934. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  41935. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  41936. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  41937. */
  41938. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41939. if (start === void 0) { start = 0; }
  41940. if (end === void 0) { end = this.nbParticles - 1; }
  41941. if (update === void 0) { update = true; }
  41942. if (!this._updatable) {
  41943. return;
  41944. }
  41945. // custom beforeUpdate
  41946. this.beforeUpdateParticles(start, end, update);
  41947. this._cam_axisX.x = 1;
  41948. this._cam_axisX.y = 0;
  41949. this._cam_axisX.z = 0;
  41950. this._cam_axisY.x = 0;
  41951. this._cam_axisY.y = 1;
  41952. this._cam_axisY.z = 0;
  41953. this._cam_axisZ.x = 0;
  41954. this._cam_axisZ.y = 0;
  41955. this._cam_axisZ.z = 1;
  41956. // if the particles will always face the camera
  41957. if (this.billboard) {
  41958. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  41959. this._yaw = this.mesh.rotation.y;
  41960. this._pitch = this.mesh.rotation.x;
  41961. this._roll = this.mesh.rotation.z;
  41962. this._quaternionRotationYPR();
  41963. this._quaternionToRotationMatrix();
  41964. this._rotMatrix.invertToRef(this._invertMatrix);
  41965. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  41966. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  41967. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  41968. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  41969. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  41970. this._cam_axisY.normalize();
  41971. this._cam_axisX.normalize();
  41972. this._cam_axisZ.normalize();
  41973. }
  41974. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41975. var idx = 0;
  41976. var index = 0;
  41977. var colidx = 0;
  41978. var colorIndex = 0;
  41979. var uvidx = 0;
  41980. var uvIndex = 0;
  41981. if (this._computeBoundingBox) {
  41982. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41983. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41984. }
  41985. // particle loop
  41986. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  41987. for (var p = start; p <= end; p++) {
  41988. this._particle = this.particles[p];
  41989. this._shape = this._particle._model._shape;
  41990. this._shapeUV = this._particle._model._shapeUV;
  41991. // call to custom user function to update the particle properties
  41992. this.updateParticle(this._particle);
  41993. // particle rotation matrix
  41994. if (this.billboard) {
  41995. this._particle.rotation.x = 0.0;
  41996. this._particle.rotation.y = 0.0;
  41997. }
  41998. if (this._computeParticleRotation) {
  41999. if (this._particle.rotationQuaternion) {
  42000. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42001. }
  42002. else {
  42003. this._yaw = this._particle.rotation.y;
  42004. this._pitch = this._particle.rotation.x;
  42005. this._roll = this._particle.rotation.z;
  42006. this._quaternionRotationYPR();
  42007. }
  42008. this._quaternionToRotationMatrix();
  42009. }
  42010. for (var pt = 0; pt < this._shape.length; pt++) {
  42011. idx = index + pt * 3;
  42012. colidx = colorIndex + pt * 4;
  42013. uvidx = uvIndex + pt * 2;
  42014. this._vertex.x = this._shape[pt].x;
  42015. this._vertex.y = this._shape[pt].y;
  42016. this._vertex.z = this._shape[pt].z;
  42017. if (this._computeParticleVertex) {
  42018. this.updateParticleVertex(this._particle, this._vertex, pt);
  42019. }
  42020. // positions
  42021. this._vertex.x *= this._particle.scaling.x;
  42022. this._vertex.y *= this._particle.scaling.y;
  42023. this._vertex.z *= this._particle.scaling.z;
  42024. 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];
  42025. 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;
  42026. 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;
  42027. 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;
  42028. 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;
  42029. 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;
  42030. 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;
  42031. if (this._computeBoundingBox) {
  42032. if (this._positions32[idx] < this._minimum.x) {
  42033. this._minimum.x = this._positions32[idx];
  42034. }
  42035. if (this._positions32[idx] > this._maximum.x) {
  42036. this._maximum.x = this._positions32[idx];
  42037. }
  42038. if (this._positions32[idx + 1] < this._minimum.y) {
  42039. this._minimum.y = this._positions32[idx + 1];
  42040. }
  42041. if (this._positions32[idx + 1] > this._maximum.y) {
  42042. this._maximum.y = this._positions32[idx + 1];
  42043. }
  42044. if (this._positions32[idx + 2] < this._minimum.z) {
  42045. this._minimum.z = this._positions32[idx + 2];
  42046. }
  42047. if (this._positions32[idx + 2] > this._maximum.z) {
  42048. this._maximum.z = this._positions32[idx + 2];
  42049. }
  42050. }
  42051. // normals : if the particles can't be morphed then just rotate the normals
  42052. if (!this._computeParticleVertex && !this.billboard) {
  42053. this._normal.x = this._fixedNormal32[idx];
  42054. this._normal.y = this._fixedNormal32[idx + 1];
  42055. this._normal.z = this._fixedNormal32[idx + 2];
  42056. 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];
  42057. 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;
  42058. 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;
  42059. 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;
  42060. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42061. 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;
  42062. 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;
  42063. }
  42064. if (this._computeParticleColor) {
  42065. this._colors32[colidx] = this._particle.color.r;
  42066. this._colors32[colidx + 1] = this._particle.color.g;
  42067. this._colors32[colidx + 2] = this._particle.color.b;
  42068. this._colors32[colidx + 3] = this._particle.color.a;
  42069. }
  42070. if (this._computeParticleTexture) {
  42071. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42072. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42073. }
  42074. }
  42075. index = idx + 3;
  42076. colorIndex = colidx + 4;
  42077. uvIndex = uvidx + 2;
  42078. }
  42079. if (update) {
  42080. if (this._computeParticleColor) {
  42081. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42082. }
  42083. if (this._computeParticleTexture) {
  42084. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42085. }
  42086. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42087. if (!this.mesh.areNormalsFrozen) {
  42088. if (this._computeParticleVertex || this.billboard) {
  42089. // recompute the normals only if the particles can be morphed, update then the normal reference array
  42090. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  42091. for (var i = 0; i < this._normals32.length; i++) {
  42092. this._fixedNormal32[i] = this._normals32[i];
  42093. }
  42094. }
  42095. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42096. }
  42097. }
  42098. if (this._computeBoundingBox) {
  42099. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42100. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42101. }
  42102. this.afterUpdateParticles(start, end, update);
  42103. };
  42104. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42105. this._halfroll = this._roll * 0.5;
  42106. this._halfpitch = this._pitch * 0.5;
  42107. this._halfyaw = this._yaw * 0.5;
  42108. this._sinRoll = Math.sin(this._halfroll);
  42109. this._cosRoll = Math.cos(this._halfroll);
  42110. this._sinPitch = Math.sin(this._halfpitch);
  42111. this._cosPitch = Math.cos(this._halfpitch);
  42112. this._sinYaw = Math.sin(this._halfyaw);
  42113. this._cosYaw = Math.cos(this._halfyaw);
  42114. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  42115. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  42116. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  42117. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  42118. };
  42119. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42120. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42121. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42122. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42123. this._rotMatrix.m[3] = 0;
  42124. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42125. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42126. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42127. this._rotMatrix.m[7] = 0;
  42128. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42129. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42130. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42131. this._rotMatrix.m[11] = 0;
  42132. this._rotMatrix.m[12] = 0;
  42133. this._rotMatrix.m[13] = 0;
  42134. this._rotMatrix.m[14] = 0;
  42135. this._rotMatrix.m[15] = 1.0;
  42136. };
  42137. /**
  42138. * Disposes the SPS
  42139. */
  42140. SolidParticleSystem.prototype.dispose = function () {
  42141. this.mesh.dispose();
  42142. this.vars = null;
  42143. // drop references to internal big arrays for the GC
  42144. this._positions = null;
  42145. this._indices = null;
  42146. this._normals = null;
  42147. this._uvs = null;
  42148. this._colors = null;
  42149. this._positions32 = null;
  42150. this._normals32 = null;
  42151. this._fixedNormal32 = null;
  42152. this._uvs32 = null;
  42153. this._colors32 = null;
  42154. this.pickedParticles = null;
  42155. };
  42156. /**
  42157. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42158. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42159. */
  42160. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42161. if (!this._isVisibilityBoxLocked) {
  42162. this.mesh.refreshBoundingInfo();
  42163. }
  42164. };
  42165. /**
  42166. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42167. * @param size the size (float) of the visibility box
  42168. * note : this doesn't lock the SPS mesh bounding box.
  42169. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42170. */
  42171. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42172. var vis = size / 2;
  42173. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42174. };
  42175. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42176. // getter and setter
  42177. get: function () {
  42178. return this._alwaysVisible;
  42179. },
  42180. /**
  42181. * Sets the SPS as always visible or not
  42182. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42183. */
  42184. set: function (val) {
  42185. this._alwaysVisible = val;
  42186. this.mesh.alwaysSelectAsActiveMesh = val;
  42187. },
  42188. enumerable: true,
  42189. configurable: true
  42190. });
  42191. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42192. get: function () {
  42193. return this._isVisibilityBoxLocked;
  42194. },
  42195. /**
  42196. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42197. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42198. */
  42199. set: function (val) {
  42200. this._isVisibilityBoxLocked = val;
  42201. this.mesh.getBoundingInfo().isLocked = val;
  42202. },
  42203. enumerable: true,
  42204. configurable: true
  42205. });
  42206. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42207. // getters
  42208. get: function () {
  42209. return this._computeParticleRotation;
  42210. },
  42211. // Optimizer setters
  42212. /**
  42213. * Tells to `setParticles()` to compute the particle rotations or not.
  42214. * Default value : true. The SPS is faster when it's set to false.
  42215. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42216. */
  42217. set: function (val) {
  42218. this._computeParticleRotation = val;
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42224. get: function () {
  42225. return this._computeParticleColor;
  42226. },
  42227. /**
  42228. * Tells to `setParticles()` to compute the particle colors or not.
  42229. * Default value : true. The SPS is faster when it's set to false.
  42230. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42231. */
  42232. set: function (val) {
  42233. this._computeParticleColor = val;
  42234. },
  42235. enumerable: true,
  42236. configurable: true
  42237. });
  42238. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42239. get: function () {
  42240. return this._computeParticleTexture;
  42241. },
  42242. /**
  42243. * Tells to `setParticles()` to compute the particle textures or not.
  42244. * Default value : true. The SPS is faster when it's set to false.
  42245. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42246. */
  42247. set: function (val) {
  42248. this._computeParticleTexture = val;
  42249. },
  42250. enumerable: true,
  42251. configurable: true
  42252. });
  42253. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42254. get: function () {
  42255. return this._computeParticleVertex;
  42256. },
  42257. /**
  42258. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42259. * Default value : false. The SPS is faster when it's set to false.
  42260. * Note : the particle custom vertex positions aren't stored values.
  42261. */
  42262. set: function (val) {
  42263. this._computeParticleVertex = val;
  42264. },
  42265. enumerable: true,
  42266. configurable: true
  42267. });
  42268. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42269. get: function () {
  42270. return this._computeBoundingBox;
  42271. },
  42272. /**
  42273. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42274. */
  42275. set: function (val) {
  42276. this._computeBoundingBox = val;
  42277. },
  42278. enumerable: true,
  42279. configurable: true
  42280. });
  42281. // =======================================================================
  42282. // Particle behavior logic
  42283. // these following methods may be overwritten by the user to fit his needs
  42284. /**
  42285. * This function does nothing. It may be overwritten to set all the particle first values.
  42286. * The SPS doesn't call this function, you may have to call it by your own.
  42287. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42288. */
  42289. SolidParticleSystem.prototype.initParticles = function () {
  42290. };
  42291. /**
  42292. * This function does nothing. It may be overwritten to recycle a particle.
  42293. * The SPS doesn't call this function, you may have to call it by your own.
  42294. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42295. */
  42296. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42297. return particle;
  42298. };
  42299. /**
  42300. * Updates a particle : this function should be overwritten by the user.
  42301. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42302. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42303. * ex : just set a particle position or velocity and recycle conditions
  42304. */
  42305. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42306. return particle;
  42307. };
  42308. /**
  42309. * Updates a vertex of a particle : it can be overwritten by the user.
  42310. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42311. * @param particle the current particle
  42312. * @param vertex the current index of the current particle
  42313. * @param pt the index of the current vertex in the particle shape
  42314. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  42315. * ex : just set a vertex particle position
  42316. */
  42317. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42318. return vertex;
  42319. };
  42320. /**
  42321. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42322. * This does nothing and may be overwritten by the user.
  42323. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42324. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42325. * @param update the boolean update value actually passed to setParticles()
  42326. */
  42327. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42328. };
  42329. /**
  42330. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42331. * This will be passed three parameters.
  42332. * This does nothing and may be overwritten by the user.
  42333. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42334. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42335. * @param update the boolean update value actually passed to setParticles()
  42336. */
  42337. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42338. };
  42339. return SolidParticleSystem;
  42340. })();
  42341. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42342. })(BABYLON || (BABYLON = {}));
  42343. var BABYLON;
  42344. (function (BABYLON) {
  42345. var Internals;
  42346. (function (Internals) {
  42347. var FileFaceOrientation = (function () {
  42348. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42349. this.name = name;
  42350. this.worldAxisForNormal = worldAxisForNormal;
  42351. this.worldAxisForFileX = worldAxisForFileX;
  42352. this.worldAxisForFileY = worldAxisForFileY;
  42353. }
  42354. return FileFaceOrientation;
  42355. })();
  42356. ;
  42357. /**
  42358. * Helper class dealing with the extraction of spherical polynomial dataArray
  42359. * from a cube map.
  42360. */
  42361. var CubeMapToSphericalPolynomialTools = (function () {
  42362. function CubeMapToSphericalPolynomialTools() {
  42363. }
  42364. /**
  42365. * Converts a cubemap to the according Spherical Polynomial data.
  42366. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42367. *
  42368. * @param cubeInfo The Cube map to extract the information from.
  42369. * @return The Spherical Polynomial data.
  42370. */
  42371. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42372. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42373. var totalSolidAngle = 0.0;
  42374. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42375. var du = 2.0 / cubeInfo.size;
  42376. var dv = du;
  42377. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42378. var minUV = du * 0.5 - 1.0;
  42379. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42380. var fileFace = this.FileFaces[faceIndex];
  42381. var dataArray = cubeInfo[fileFace.name];
  42382. var v = minUV;
  42383. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42384. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42385. // Because SP is still linear, so summation is fine in that basis.
  42386. for (var y = 0; y < cubeInfo.size; y++) {
  42387. var u = minUV;
  42388. for (var x = 0; x < cubeInfo.size; x++) {
  42389. // World direction (not normalised)
  42390. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42391. worldDirection.normalize();
  42392. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42393. if (1) {
  42394. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  42395. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  42396. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  42397. var color = new BABYLON.Color3(r, g, b);
  42398. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42399. }
  42400. else {
  42401. if (faceIndex == 0) {
  42402. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42403. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42404. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42405. }
  42406. else if (faceIndex == 1) {
  42407. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42408. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42409. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42410. }
  42411. else if (faceIndex == 2) {
  42412. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42413. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42414. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42415. }
  42416. else if (faceIndex == 3) {
  42417. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42418. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42419. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42420. }
  42421. else if (faceIndex == 4) {
  42422. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42423. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42424. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42425. }
  42426. else if (faceIndex == 5) {
  42427. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42428. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42429. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42430. }
  42431. 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]);
  42432. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42433. }
  42434. totalSolidAngle += deltaSolidAngle;
  42435. u += du;
  42436. }
  42437. v += dv;
  42438. }
  42439. }
  42440. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  42441. var correction = correctSolidAngle / totalSolidAngle;
  42442. sphericalHarmonics.scale(correction);
  42443. // Additionally scale by pi -- audit needed
  42444. sphericalHarmonics.scale(1.0 / Math.PI);
  42445. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  42446. };
  42447. CubeMapToSphericalPolynomialTools.FileFaces = [
  42448. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  42449. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  42450. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  42451. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  42452. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  42453. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  42454. ];
  42455. return CubeMapToSphericalPolynomialTools;
  42456. })();
  42457. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  42458. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42459. })(BABYLON || (BABYLON = {}));
  42460. var BABYLON;
  42461. (function (BABYLON) {
  42462. var Internals;
  42463. (function (Internals) {
  42464. /**
  42465. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  42466. */
  42467. var PanoramaToCubeMapTools = (function () {
  42468. function PanoramaToCubeMapTools() {
  42469. }
  42470. /**
  42471. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  42472. *
  42473. * @param float32Array The source data.
  42474. * @param inputWidth The width of the input panorama.
  42475. * @param inputhHeight The height of the input panorama.
  42476. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  42477. * @return The cubemap data
  42478. */
  42479. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  42480. if (!float32Array) {
  42481. throw "ConvertPanoramaToCubemap: input cannot be null";
  42482. }
  42483. if (float32Array.length != inputWidth * inputHeight * 3) {
  42484. throw "ConvertPanoramaToCubemap: input size is wrong";
  42485. }
  42486. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  42487. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  42488. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  42489. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  42490. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  42491. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  42492. return {
  42493. front: textureFront,
  42494. back: textureBack,
  42495. left: textureLeft,
  42496. right: textureRight,
  42497. up: textureUp,
  42498. down: textureDown,
  42499. size: size
  42500. };
  42501. };
  42502. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  42503. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  42504. var textureArray = new Float32Array(buffer);
  42505. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  42506. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  42507. var dy = 1 / texSize;
  42508. var fy = 0;
  42509. for (var y = 0; y < texSize; y++) {
  42510. var xv1 = faceData[0];
  42511. var xv2 = faceData[2];
  42512. for (var x = 0; x < texSize; x++) {
  42513. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  42514. v.normalize();
  42515. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  42516. // 3 channels per pixels
  42517. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  42518. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  42519. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  42520. xv1 = xv1.add(rotDX1);
  42521. xv2 = xv2.add(rotDX2);
  42522. }
  42523. fy += dy;
  42524. }
  42525. return textureArray;
  42526. };
  42527. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  42528. var theta = Math.atan2(vDir.z, vDir.x);
  42529. var phi = Math.acos(vDir.y);
  42530. while (theta < -Math.PI)
  42531. theta += 2 * Math.PI;
  42532. while (theta > Math.PI)
  42533. theta -= 2 * Math.PI;
  42534. var dx = theta / Math.PI;
  42535. var dy = phi / Math.PI;
  42536. // recenter.
  42537. dx = dx * 0.5 + 0.5;
  42538. var px = Math.round(dx * inputWidth);
  42539. if (px < 0)
  42540. px = 0;
  42541. else if (px >= inputWidth)
  42542. px = inputWidth - 1;
  42543. var py = Math.round(dy * inputHeight);
  42544. if (py < 0)
  42545. py = 0;
  42546. else if (py >= inputHeight)
  42547. py = inputHeight - 1;
  42548. var inputY = (inputHeight - py - 1);
  42549. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  42550. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  42551. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  42552. return {
  42553. r: r,
  42554. g: g,
  42555. b: b
  42556. };
  42557. };
  42558. PanoramaToCubeMapTools.FACE_FRONT = [
  42559. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42560. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42561. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42562. new BABYLON.Vector3(1.0, 1.0, -1.0)
  42563. ];
  42564. PanoramaToCubeMapTools.FACE_BACK = [
  42565. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42566. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42567. new BABYLON.Vector3(1.0, 1.0, 1.0),
  42568. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  42569. ];
  42570. PanoramaToCubeMapTools.FACE_RIGHT = [
  42571. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42572. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42573. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42574. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42575. ];
  42576. PanoramaToCubeMapTools.FACE_LEFT = [
  42577. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42578. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42579. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42580. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  42581. ];
  42582. PanoramaToCubeMapTools.FACE_DOWN = [
  42583. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42584. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42585. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42586. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42587. ];
  42588. PanoramaToCubeMapTools.FACE_UP = [
  42589. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42590. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42591. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42592. new BABYLON.Vector3(1.0, -1.0, -1.0)
  42593. ];
  42594. return PanoramaToCubeMapTools;
  42595. })();
  42596. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  42597. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42598. })(BABYLON || (BABYLON = {}));
  42599. var BABYLON;
  42600. (function (BABYLON) {
  42601. var Internals;
  42602. (function (Internals) {
  42603. ;
  42604. /**
  42605. * This groups tools to convert HDR texture to native colors array.
  42606. */
  42607. var HDRTools = (function () {
  42608. function HDRTools() {
  42609. }
  42610. HDRTools.Ldexp = function (mantissa, exponent) {
  42611. if (exponent > 1023) {
  42612. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  42613. }
  42614. if (exponent < -1074) {
  42615. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  42616. }
  42617. return mantissa * Math.pow(2, exponent);
  42618. };
  42619. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  42620. if (exponent > 0) {
  42621. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  42622. float32array[index + 0] = red * exponent;
  42623. float32array[index + 1] = green * exponent;
  42624. float32array[index + 2] = blue * exponent;
  42625. }
  42626. else {
  42627. float32array[index + 0] = 0;
  42628. float32array[index + 1] = 0;
  42629. float32array[index + 2] = 0;
  42630. }
  42631. };
  42632. HDRTools.readStringLine = function (uint8array, startIndex) {
  42633. var line = "";
  42634. var character = "";
  42635. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  42636. character = String.fromCharCode(uint8array[i]);
  42637. if (character == "\n") {
  42638. break;
  42639. }
  42640. line += character;
  42641. }
  42642. return line;
  42643. };
  42644. /**
  42645. * Reads header information from an RGBE texture stored in a native array.
  42646. * More information on this format are available here:
  42647. * https://en.wikipedia.org/wiki/RGBE_image_format
  42648. *
  42649. * @param uint8array The binary file stored in native array.
  42650. * @return The header information.
  42651. */
  42652. HDRTools.RGBE_ReadHeader = function (uint8array) {
  42653. var height = 0;
  42654. var width = 0;
  42655. var line = this.readStringLine(uint8array, 0);
  42656. if (line[0] != '#' || line[1] != '?') {
  42657. throw "Bad HDR Format.";
  42658. }
  42659. var endOfHeader = false;
  42660. var findFormat = false;
  42661. var lineIndex = 0;
  42662. do {
  42663. lineIndex += (line.length + 1);
  42664. line = this.readStringLine(uint8array, lineIndex);
  42665. if (line == "FORMAT=32-bit_rle_rgbe") {
  42666. findFormat = true;
  42667. }
  42668. else if (line.length == 0) {
  42669. endOfHeader = true;
  42670. }
  42671. } while (!endOfHeader);
  42672. if (!findFormat) {
  42673. throw "HDR Bad header format, unsupported FORMAT";
  42674. }
  42675. lineIndex += (line.length + 1);
  42676. line = this.readStringLine(uint8array, lineIndex);
  42677. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  42678. var match = sizeRegexp.exec(line);
  42679. // TODO. Support +Y and -X if needed.
  42680. if (match.length < 3) {
  42681. throw "HDR Bad header format, no size";
  42682. }
  42683. width = parseInt(match[2]);
  42684. height = parseInt(match[1]);
  42685. if (width < 8 || width > 0x7fff) {
  42686. throw "HDR Bad header format, unsupported size";
  42687. }
  42688. lineIndex += (line.length + 1);
  42689. return {
  42690. height: height,
  42691. width: width,
  42692. dataPosition: lineIndex
  42693. };
  42694. };
  42695. /**
  42696. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  42697. * This RGBE texture needs to store the information as a panorama.
  42698. *
  42699. * More information on this format are available here:
  42700. * https://en.wikipedia.org/wiki/RGBE_image_format
  42701. *
  42702. * @param buffer The binary file stored in an array buffer.
  42703. * @param size The expected size of the extracted cubemap.
  42704. * @return The Cube Map information.
  42705. */
  42706. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  42707. var uint8array = new Uint8Array(buffer);
  42708. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  42709. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42710. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  42711. return cubeMapData;
  42712. };
  42713. /**
  42714. * Returns the pixels data extracted from an RGBE texture.
  42715. * This pixels will be stored left to right up to down in the R G B order in one array.
  42716. *
  42717. * More information on this format are available here:
  42718. * https://en.wikipedia.org/wiki/RGBE_image_format
  42719. *
  42720. * @param uint8array The binary file stored in an array buffer.
  42721. * @param hdrInfo The header information of the file.
  42722. * @return The pixels data in RGB right to left up to down order.
  42723. */
  42724. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  42725. // Keep for multi format supports.
  42726. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42727. };
  42728. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  42729. var num_scanlines = hdrInfo.height;
  42730. var scanline_width = hdrInfo.width;
  42731. var a, b, c, d, count;
  42732. var dataIndex = hdrInfo.dataPosition;
  42733. var index = 0, endIndex = 0, i = 0;
  42734. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  42735. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  42736. // 3 channels of 4 bytes per pixel in float.
  42737. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  42738. var resultArray = new Float32Array(resultBuffer);
  42739. // read in each successive scanline
  42740. while (num_scanlines > 0) {
  42741. a = uint8array[dataIndex++];
  42742. b = uint8array[dataIndex++];
  42743. c = uint8array[dataIndex++];
  42744. d = uint8array[dataIndex++];
  42745. if (a != 2 || b != 2 || (c & 0x80)) {
  42746. // this file is not run length encoded
  42747. throw "HDR Bad header format, not RLE";
  42748. }
  42749. if (((c << 8) | d) != scanline_width) {
  42750. throw "HDR Bad header format, wrong scan line width";
  42751. }
  42752. index = 0;
  42753. // read each of the four channels for the scanline into the buffer
  42754. for (i = 0; i < 4; i++) {
  42755. endIndex = (i + 1) * scanline_width;
  42756. while (index < endIndex) {
  42757. a = uint8array[dataIndex++];
  42758. b = uint8array[dataIndex++];
  42759. if (a > 128) {
  42760. // a run of the same value
  42761. count = a - 128;
  42762. if ((count == 0) || (count > endIndex - index)) {
  42763. throw "HDR Bad Format, bad scanline data (run)";
  42764. }
  42765. while (count-- > 0) {
  42766. scanLineArray[index++] = b;
  42767. }
  42768. }
  42769. else {
  42770. // a non-run
  42771. count = a;
  42772. if ((count == 0) || (count > endIndex - index)) {
  42773. throw "HDR Bad Format, bad scanline data (non-run)";
  42774. }
  42775. scanLineArray[index++] = b;
  42776. if (--count > 0) {
  42777. for (var j = 0; j < count; j++) {
  42778. scanLineArray[index++] = uint8array[dataIndex++];
  42779. }
  42780. }
  42781. }
  42782. }
  42783. }
  42784. // now convert data from buffer into floats
  42785. for (i = 0; i < scanline_width; i++) {
  42786. a = scanLineArray[i];
  42787. b = scanLineArray[i + scanline_width];
  42788. c = scanLineArray[i + 2 * scanline_width];
  42789. d = scanLineArray[i + 3 * scanline_width];
  42790. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  42791. }
  42792. num_scanlines--;
  42793. }
  42794. return resultArray;
  42795. };
  42796. return HDRTools;
  42797. })();
  42798. Internals.HDRTools = HDRTools;
  42799. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42800. })(BABYLON || (BABYLON = {}));
  42801. //_______________________________________________________________
  42802. // Extracted from CubeMapGen:
  42803. // https://code.google.com/archive/p/cubemapgen/
  42804. //
  42805. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42806. //_______________________________________________________________
  42807. var BABYLON;
  42808. (function (BABYLON) {
  42809. var Internals;
  42810. (function (Internals) {
  42811. /**
  42812. * The bounding box information used during the conversion process.
  42813. */
  42814. var CMGBoundinBox = (function () {
  42815. function CMGBoundinBox() {
  42816. this.min = new BABYLON.Vector3(0, 0, 0);
  42817. this.max = new BABYLON.Vector3(0, 0, 0);
  42818. this.clear();
  42819. }
  42820. CMGBoundinBox.prototype.clear = function () {
  42821. this.min.x = CMGBoundinBox.MAX;
  42822. this.min.y = CMGBoundinBox.MAX;
  42823. this.min.z = CMGBoundinBox.MAX;
  42824. this.max.x = CMGBoundinBox.MIN;
  42825. this.max.y = CMGBoundinBox.MIN;
  42826. this.max.z = CMGBoundinBox.MIN;
  42827. };
  42828. CMGBoundinBox.prototype.augment = function (x, y, z) {
  42829. this.min.x = Math.min(this.min.x, x);
  42830. this.min.y = Math.min(this.min.y, y);
  42831. this.min.z = Math.min(this.min.z, z);
  42832. this.max.x = Math.max(this.max.x, x);
  42833. this.max.y = Math.max(this.max.y, y);
  42834. this.max.z = Math.max(this.max.z, z);
  42835. };
  42836. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  42837. this.min.x = Math.max(this.min.x, x);
  42838. this.min.y = Math.max(this.min.y, y);
  42839. this.min.z = Math.max(this.min.z, z);
  42840. };
  42841. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  42842. this.max.x = Math.min(this.max.x, x);
  42843. this.max.y = Math.min(this.max.y, y);
  42844. this.max.z = Math.min(this.max.z, z);
  42845. };
  42846. CMGBoundinBox.prototype.empty = function () {
  42847. if ((this.min.x > this.max.y) ||
  42848. (this.min.y > this.max.y) ||
  42849. (this.min.z > this.max.y)) {
  42850. return true;
  42851. }
  42852. else {
  42853. return false;
  42854. }
  42855. };
  42856. CMGBoundinBox.MAX = Number.MAX_VALUE;
  42857. CMGBoundinBox.MIN = Number.MIN_VALUE;
  42858. return CMGBoundinBox;
  42859. })();
  42860. /**
  42861. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  42862. * required by the glossinees of a material.
  42863. *
  42864. * This only supports the cosine drop power as well as Warp fixup generation method.
  42865. *
  42866. * This is using the process from CubeMapGen described here:
  42867. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42868. */
  42869. var PMREMGenerator = (function () {
  42870. /**
  42871. * Constructor of the generator.
  42872. *
  42873. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  42874. * @param inputSize The size of the cubemap faces
  42875. * @param outputSize The size of the output cubemap faces
  42876. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  42877. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  42878. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  42879. * @param specularPower The max specular level of the desired cubemap
  42880. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  42881. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  42882. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  42883. */
  42884. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  42885. this.input = input;
  42886. this.inputSize = inputSize;
  42887. this.outputSize = outputSize;
  42888. this.maxNumMipLevels = maxNumMipLevels;
  42889. this.numChannels = numChannels;
  42890. this.isFloat = isFloat;
  42891. this.specularPower = specularPower;
  42892. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  42893. this.excludeBase = excludeBase;
  42894. this.fixup = fixup;
  42895. this._outputSurface = [];
  42896. this._numMipLevels = 0;
  42897. }
  42898. /**
  42899. * Launches the filter process and return the result.
  42900. *
  42901. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  42902. */
  42903. PMREMGenerator.prototype.filterCubeMap = function () {
  42904. // Init cubemap processor
  42905. this.init();
  42906. // Filters the cubemap
  42907. this.filterCubeMapMipChain();
  42908. // Returns the filtered mips.
  42909. return this._outputSurface;
  42910. };
  42911. PMREMGenerator.prototype.init = function () {
  42912. var i;
  42913. var j;
  42914. var mipLevelSize;
  42915. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  42916. if (this.maxNumMipLevels == 0) {
  42917. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  42918. }
  42919. //first miplevel size
  42920. mipLevelSize = this.outputSize;
  42921. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  42922. for (j = 0; j < this.maxNumMipLevels; j++) {
  42923. this._outputSurface.length++;
  42924. this._outputSurface[j] = [];
  42925. //Iterate over faces for output images
  42926. for (i = 0; i < 6; i++) {
  42927. this._outputSurface[j].length++;
  42928. // Initializes a new array for the output.
  42929. if (this.isFloat) {
  42930. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42931. }
  42932. else {
  42933. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42934. }
  42935. }
  42936. //next mip level is half size
  42937. mipLevelSize >>= 1;
  42938. this._numMipLevels++;
  42939. //terminate if mip chain becomes too small
  42940. if (mipLevelSize == 0) {
  42941. this.maxNumMipLevels = j;
  42942. return;
  42943. }
  42944. }
  42945. };
  42946. //--------------------------------------------------------------------------------------
  42947. //Cube map filtering and mip chain generation.
  42948. // the cube map filtereing is specified using a number of parameters:
  42949. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  42950. // indicates the region of the hemisphere to filter over for each tap.
  42951. //
  42952. // Note that the top mip level is also a filtered version of the original input images
  42953. // as well in order to create mip chains for diffuse environment illumination.
  42954. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  42955. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  42956. //
  42957. // Then the mip angle used to genreate the next level of the mip chain from the first level
  42958. // is a_InitialMipAngle
  42959. //
  42960. // The angle for the subsequent levels of the mip chain are specified by their parents
  42961. // filtering angle and a per-level scale and bias
  42962. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  42963. //
  42964. //--------------------------------------------------------------------------------------
  42965. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  42966. // First, take count of the lighting model to modify SpecularPower
  42967. // 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;
  42968. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  42969. //Cone angle start (for generating subsequent mip levels)
  42970. var currentSpecularPower = this.specularPower;
  42971. //Build filter lookup tables based on the source miplevel size
  42972. this.precomputeFilterLookupTables(this.inputSize);
  42973. // Note that we need to filter the first level before generating mipmap
  42974. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  42975. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  42976. // TODO : Write a function to copy and scale the base mipmap in output
  42977. // I am just lazy here and just put a high specular power value, and do some if.
  42978. if (this.excludeBase && (levelIndex == 0)) {
  42979. // 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).
  42980. currentSpecularPower = 100000.0;
  42981. }
  42982. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  42983. var srcCubeImage = this.input;
  42984. var dstCubeImage = this._outputSurface[levelIndex];
  42985. var dstSize = this.outputSize >> levelIndex;
  42986. // Compute required angle.
  42987. var angle = this.getBaseFilterAngle(currentSpecularPower);
  42988. // filter cube surfaces
  42989. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  42990. // fix seams
  42991. if (this.fixup) {
  42992. this.fixupCubeEdges(dstCubeImage, dstSize);
  42993. }
  42994. // Decrease the specular power to generate the mipmap chain
  42995. // TODO : Use another method for Exclude (see first comment at start of the function
  42996. if (this.excludeBase && (levelIndex == 0)) {
  42997. currentSpecularPower = this.specularPower;
  42998. }
  42999. currentSpecularPower *= this.cosinePowerDropPerMip;
  43000. }
  43001. };
  43002. //--------------------------------------------------------------------------------------
  43003. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  43004. // It allow to optimize the texel to access base on the specular power.
  43005. //--------------------------------------------------------------------------------------
  43006. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  43007. // We want to find the alpha such that:
  43008. // cos(alpha)^cosinePower = epsilon
  43009. // That's: acos(epsilon^(1/cosinePower))
  43010. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  43011. var angle = 180.0;
  43012. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  43013. angle *= 180.0 / Math.PI; // Convert to degree
  43014. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  43015. return angle;
  43016. };
  43017. //--------------------------------------------------------------------------------------
  43018. //Builds the following lookup tables prior to filtering:
  43019. // -normalizer cube map
  43020. // -tap weight lookup table
  43021. //
  43022. //--------------------------------------------------------------------------------------
  43023. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  43024. var srcTexelAngle;
  43025. var iCubeFace;
  43026. //clear pre-existing normalizer cube map
  43027. this._normCubeMap = [];
  43028. //Normalized vectors per cubeface and per-texel solid angle
  43029. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  43030. };
  43031. //--------------------------------------------------------------------------------------
  43032. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  43033. //
  43034. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  43035. //
  43036. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  43037. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  43038. // below
  43039. //--------------------------------------------------------------------------------------
  43040. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  43041. var iCubeFace;
  43042. var u;
  43043. var v;
  43044. //iterate over cube faces
  43045. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43046. //First three channels for norm cube, and last channel for solid angle
  43047. this._normCubeMap.push(new Float32Array(size * size * 4));
  43048. //fast texture walk, build normalizer cube map
  43049. var facesData = this.input[iCubeFace];
  43050. for (v = 0; v < size; v++) {
  43051. for (u = 0; u < size; u++) {
  43052. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  43053. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  43054. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  43055. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  43056. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  43057. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  43058. }
  43059. }
  43060. }
  43061. };
  43062. //--------------------------------------------------------------------------------------
  43063. // Convert cubemap face texel coordinates and face idx to 3D vector
  43064. // note the U and V coords are integer coords and range from 0 to size-1
  43065. // this routine can be used to generate a normalizer cube map
  43066. //--------------------------------------------------------------------------------------
  43067. // SL BEGIN
  43068. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  43069. var nvcU;
  43070. var nvcV;
  43071. var tempVec;
  43072. // Change from original AMD code
  43073. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43074. // + 0.5f is for texel center addressing
  43075. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  43076. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  43077. // warp fixup
  43078. if (fixup && size > 1) {
  43079. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  43080. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  43081. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  43082. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  43083. }
  43084. // Get current vector
  43085. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  43086. // U contribution
  43087. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43088. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  43089. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  43090. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  43091. // V contribution and Sum
  43092. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43093. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  43094. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  43095. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  43096. //add face axis
  43097. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  43098. PMREMGenerator._vectorTemp.x += faceAxis[0];
  43099. PMREMGenerator._vectorTemp.y += faceAxis[1];
  43100. PMREMGenerator._vectorTemp.z += faceAxis[2];
  43101. //normalize vector
  43102. PMREMGenerator._vectorTemp.normalize();
  43103. return PMREMGenerator._vectorTemp;
  43104. };
  43105. //--------------------------------------------------------------------------------------
  43106. // Convert 3D vector to cubemap face texel coordinates and face idx
  43107. // note the U and V coords are integer coords and range from 0 to size-1
  43108. // this routine can be used to generate a normalizer cube map
  43109. //
  43110. // returns face IDX and texel coords
  43111. //--------------------------------------------------------------------------------------
  43112. // SL BEGIN
  43113. /*
  43114. Mapping Texture Coordinates to Cube Map Faces
  43115. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  43116. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  43117. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  43118. map arrangement in Pixar's RenderMan package.
  43119. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  43120. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  43121. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  43122. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  43123. the major axis direction). The target column in the table below explains how the major axis direction
  43124. maps to the 2D image of a particular cube map target.
  43125. major axis
  43126. direction target sc tc ma
  43127. ---------- --------------------------------- --- --- ---
  43128. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  43129. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  43130. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  43131. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  43132. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  43133. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  43134. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  43135. an updated (s,t) is calculated as follows
  43136. s = ( sc/|ma| + 1 ) / 2
  43137. t = ( tc/|ma| + 1 ) / 2
  43138. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  43139. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  43140. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  43141. */
  43142. // Note this method return U and V in range from 0 to size-1
  43143. // SL END
  43144. // Store the information in vector3 for convenience (faceindex, u, v)
  43145. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  43146. var maxCoord;
  43147. var faceIdx;
  43148. //absolute value 3
  43149. var absX = Math.abs(x);
  43150. var absY = Math.abs(y);
  43151. var absZ = Math.abs(z);
  43152. if (absX >= absY && absX >= absZ) {
  43153. maxCoord = absX;
  43154. if (x >= 0) {
  43155. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  43156. }
  43157. else {
  43158. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43159. }
  43160. }
  43161. else if (absY >= absX && absY >= absZ) {
  43162. maxCoord = absY;
  43163. if (y >= 0) {
  43164. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43165. }
  43166. else {
  43167. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43168. }
  43169. }
  43170. else {
  43171. maxCoord = absZ;
  43172. if (z >= 0) {
  43173. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43174. }
  43175. else {
  43176. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43177. }
  43178. }
  43179. //divide through by max coord so face vector lies on cube face
  43180. var scale = 1 / maxCoord;
  43181. x *= scale;
  43182. y *= scale;
  43183. z *= scale;
  43184. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43185. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  43186. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43187. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  43188. // Modify original AMD code to return value from 0 to Size - 1
  43189. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  43190. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  43191. PMREMGenerator._vectorTemp.x = faceIdx;
  43192. PMREMGenerator._vectorTemp.y = u;
  43193. PMREMGenerator._vectorTemp.z = v;
  43194. return PMREMGenerator._vectorTemp;
  43195. };
  43196. //--------------------------------------------------------------------------------------
  43197. //Original code from Ignacio CastaÒo
  43198. // This formula is from Manne ÷hrstrˆm's thesis.
  43199. // Take two coordiantes in the range [-1, 1] that define a portion of a
  43200. // cube face and return the area of the projection of that portion on the
  43201. // surface of the sphere.
  43202. //--------------------------------------------------------------------------------------
  43203. PMREMGenerator.prototype.areaElement = function (x, y) {
  43204. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  43205. };
  43206. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  43207. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43208. // (+ 0.5f is for texel center addressing)
  43209. u = (2.0 * (u + 0.5) / size) - 1.0;
  43210. v = (2.0 * (v + 0.5) / size) - 1.0;
  43211. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  43212. var invResolution = 1.0 / size;
  43213. // U and V are the -1..1 texture coordinate on the current face.
  43214. // Get projected area for this texel
  43215. var x0 = u - invResolution;
  43216. var y0 = v - invResolution;
  43217. var x1 = u + invResolution;
  43218. var y1 = v + invResolution;
  43219. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  43220. return solidAngle;
  43221. };
  43222. //--------------------------------------------------------------------------------------
  43223. //The key to the speed of these filtering routines is to quickly define a per-face
  43224. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  43225. // Later these pixels are selectively processed based on their dot products to see if
  43226. // they reside within the filtering cone.
  43227. //
  43228. //This is done by computing the smallest per-texel angle to get a conservative estimate
  43229. // of the number of texels needed to be covered in width and height order to filter the
  43230. // region. the bounding box for the center taps face is defined first, and if the
  43231. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  43232. // defined next
  43233. //--------------------------------------------------------------------------------------
  43234. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  43235. // note that pixels within these regions may be rejected
  43236. // based on the anlge
  43237. var iCubeFace;
  43238. var u;
  43239. var v;
  43240. // bounding box per face to specify region to process
  43241. var filterExtents = [];
  43242. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43243. filterExtents.push(new CMGBoundinBox());
  43244. }
  43245. // min angle a src texel can cover (in degrees)
  43246. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  43247. // angle about center tap to define filter cone
  43248. // filter angle is 1/2 the cone angle
  43249. var filterAngle = filterConeAngle / 2.0;
  43250. //ensure filter angle is larger than a texel
  43251. if (filterAngle < srcTexelAngle) {
  43252. filterAngle = srcTexelAngle;
  43253. }
  43254. //ensure filter cone is always smaller than the hemisphere
  43255. if (filterAngle > 90.0) {
  43256. filterAngle = 90.0;
  43257. }
  43258. // the maximum number of texels in 1D the filter cone angle will cover
  43259. // used to determine bounding box size for filter extents
  43260. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  43261. // ensure conservative region always covers at least one texel
  43262. if (filterSize < 1) {
  43263. filterSize = 1;
  43264. }
  43265. // dotProdThresh threshold based on cone angle to determine whether or not taps
  43266. // reside within the cone angle
  43267. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  43268. // process required faces
  43269. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43270. //iterate over dst cube map face texel
  43271. for (v = 0; v < dstSize; v++) {
  43272. for (u = 0; u < dstSize; u++) {
  43273. //get center tap direction
  43274. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  43275. //clear old per-face filter extents
  43276. this.clearFilterExtents(filterExtents);
  43277. //define per-face filter extents
  43278. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  43279. //perform filtering of src faces using filter extents
  43280. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  43281. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  43282. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  43283. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  43284. }
  43285. }
  43286. }
  43287. };
  43288. //--------------------------------------------------------------------------------------
  43289. //Clear filter extents for the 6 cube map faces
  43290. //--------------------------------------------------------------------------------------
  43291. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  43292. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  43293. filterExtents[iCubeFaces].clear();
  43294. }
  43295. };
  43296. //--------------------------------------------------------------------------------------
  43297. //Define per-face bounding box filter extents
  43298. //
  43299. // These define conservative texel regions in each of the faces the filter can possibly
  43300. // process. When the pixels in the regions are actually processed, the dot product
  43301. // between the tap vector and the center tap vector is used to determine the weight of
  43302. // the tap and whether or not the tap is within the cone.
  43303. //
  43304. //--------------------------------------------------------------------------------------
  43305. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  43306. //neighboring face and bleed over amount, and width of BBOX for
  43307. // left, right, top, and bottom edges of this face
  43308. var bleedOverAmount = [0, 0, 0, 0];
  43309. var bleedOverBBoxMin = [0, 0, 0, 0];
  43310. var bleedOverBBoxMax = [0, 0, 0, 0];
  43311. var neighborFace;
  43312. var neighborEdge;
  43313. var oppositeFaceIdx;
  43314. //get face idx, and u, v info from center tap dir
  43315. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  43316. var faceIdx = result.x;
  43317. var u = result.y;
  43318. var v = result.z;
  43319. //define bbox size within face
  43320. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  43321. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  43322. filterExtents[faceIdx].clampMin(0, 0, 0);
  43323. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  43324. //u and v extent in face corresponding to center tap
  43325. var minU = filterExtents[faceIdx].min.x;
  43326. var minV = filterExtents[faceIdx].min.y;
  43327. var maxU = filterExtents[faceIdx].max.x;
  43328. var maxV = filterExtents[faceIdx].max.y;
  43329. //bleed over amounts for face across u=0 edge (left)
  43330. bleedOverAmount[0] = (bboxSize - u);
  43331. bleedOverBBoxMin[0] = minV;
  43332. bleedOverBBoxMax[0] = maxV;
  43333. //bleed over amounts for face across u=1 edge (right)
  43334. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  43335. bleedOverBBoxMin[1] = minV;
  43336. bleedOverBBoxMax[1] = maxV;
  43337. //bleed over to face across v=0 edge (up)
  43338. bleedOverAmount[2] = (bboxSize - v);
  43339. bleedOverBBoxMin[2] = minU;
  43340. bleedOverBBoxMax[2] = maxU;
  43341. //bleed over to face across v=1 edge (down)
  43342. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  43343. bleedOverBBoxMin[3] = minU;
  43344. bleedOverBBoxMax[3] = maxU;
  43345. //compute bleed over regions in neighboring faces
  43346. for (var i = 0; i < 4; i++) {
  43347. if (bleedOverAmount[i] > 0) {
  43348. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  43349. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  43350. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  43351. // be flipped: the cases are
  43352. // if a left edge mates with a left or bottom edge on the neighbor
  43353. // if a top edge mates with a top or right edge on the neighbor
  43354. // if a right edge mates with a right or top edge on the neighbor
  43355. // if a bottom edge mates with a bottom or left edge on the neighbor
  43356. //Seeing as the edges are enumerated as follows
  43357. // left =0
  43358. // right =1
  43359. // top =2
  43360. // bottom =3
  43361. //
  43362. // so if the edge enums are the same, or the sum of the enums == 3,
  43363. // the bbox needs to be flipped
  43364. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  43365. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  43366. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  43367. }
  43368. //The way the bounding box is extended onto the neighboring face
  43369. // depends on which edge of neighboring face abuts with this one
  43370. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  43371. case PMREMGenerator.CP_EDGE_LEFT:
  43372. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  43373. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43374. break;
  43375. case PMREMGenerator.CP_EDGE_RIGHT:
  43376. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  43377. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43378. break;
  43379. case PMREMGenerator.CP_EDGE_TOP:
  43380. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  43381. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  43382. break;
  43383. case PMREMGenerator.CP_EDGE_BOTTOM:
  43384. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  43385. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  43386. break;
  43387. }
  43388. //clamp filter extents in non-center tap faces to remain within surface
  43389. filterExtents[neighborFace].clampMin(0, 0, 0);
  43390. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  43391. }
  43392. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  43393. // from the center tap face, then process the opposite face entirely for now.
  43394. //Note that the cases in which this happens, what usually happens is that
  43395. // more than one edge bleeds onto the opposite face, and the bounding box
  43396. // encompasses the entire cube map face.
  43397. if (bleedOverAmount[i] > srcSize) {
  43398. //determine opposite face
  43399. switch (faceIdx) {
  43400. case PMREMGenerator.CP_FACE_X_POS:
  43401. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43402. break;
  43403. case PMREMGenerator.CP_FACE_X_NEG:
  43404. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  43405. break;
  43406. case PMREMGenerator.CP_FACE_Y_POS:
  43407. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43408. break;
  43409. case PMREMGenerator.CP_FACE_Y_NEG:
  43410. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43411. break;
  43412. case PMREMGenerator.CP_FACE_Z_POS:
  43413. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43414. break;
  43415. case PMREMGenerator.CP_FACE_Z_NEG:
  43416. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43417. break;
  43418. default:
  43419. break;
  43420. }
  43421. //just encompass entire face for now
  43422. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  43423. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  43424. }
  43425. }
  43426. };
  43427. //--------------------------------------------------------------------------------------
  43428. //ProcessFilterExtents
  43429. // Process bounding box in each cube face
  43430. //
  43431. //--------------------------------------------------------------------------------------
  43432. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  43433. //accumulators are 64-bit floats in order to have the precision needed
  43434. // over a summation of a large number of pixels
  43435. var dstAccum = [0, 0, 0, 0];
  43436. var weightAccum = 0;
  43437. var k = 0;
  43438. var nSrcChannels = this.numChannels;
  43439. // norm cube map and srcCubeMap have same face width
  43440. var faceWidth = srcSize;
  43441. //amount to add to pointer to move to next scanline in images
  43442. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  43443. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  43444. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  43445. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  43446. // iterate over cubefaces
  43447. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  43448. //if bbox is non empty
  43449. if (!filterExtents[iFaceIdx].empty()) {
  43450. var uStart = filterExtents[iFaceIdx].min.x;
  43451. var vStart = filterExtents[iFaceIdx].min.y;
  43452. var uEnd = filterExtents[iFaceIdx].max.x;
  43453. var vEnd = filterExtents[iFaceIdx].max.y;
  43454. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  43455. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  43456. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  43457. for (var v = vStart; v <= vEnd; v++) {
  43458. var normCubeRowWalk = 0;
  43459. var srcCubeRowWalk = 0;
  43460. for (var u = uStart; u <= uEnd; u++) {
  43461. //pointer to direction in cube map associated with texel
  43462. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  43463. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  43464. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  43465. //check dot product to see if texel is within cone
  43466. var tapDotProd = texelVectX * centerTapDir.x +
  43467. texelVectY * centerTapDir.y +
  43468. texelVectZ * centerTapDir.z;
  43469. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  43470. //solid angle stored in 4th channel of normalizer/solid angle cube map
  43471. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  43472. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  43473. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  43474. // so just adding one to specularpower do the trick.
  43475. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  43476. //iterate over channels
  43477. for (k = 0; k < nSrcChannels; k++) {
  43478. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  43479. srcCubeRowWalk++;
  43480. }
  43481. weightAccum += weight; //accumulate weight
  43482. }
  43483. else {
  43484. //step across source pixel
  43485. srcCubeRowWalk += nSrcChannels;
  43486. }
  43487. normCubeRowWalk += 4; // 4 channels per norm cube map.
  43488. }
  43489. startIndexNormCubeMap += normCubePitch;
  43490. startIndexSrcCubeMap += srcCubePitch;
  43491. }
  43492. }
  43493. }
  43494. //divide through by weights if weight is non zero
  43495. if (weightAccum != 0.0) {
  43496. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  43497. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  43498. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  43499. if (this.numChannels > 3) {
  43500. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  43501. }
  43502. }
  43503. else {
  43504. // otherwise sample nearest
  43505. // get face idx and u, v texel coordinate in face
  43506. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  43507. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  43508. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  43509. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  43510. if (this.numChannels > 3) {
  43511. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  43512. }
  43513. }
  43514. return PMREMGenerator._vectorTemp;
  43515. };
  43516. //--------------------------------------------------------------------------------------
  43517. // Fixup cube edges
  43518. //
  43519. // average texels on cube map faces across the edges
  43520. // WARP/BENT Method Only.
  43521. //--------------------------------------------------------------------------------------
  43522. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  43523. var k;
  43524. var j;
  43525. var i;
  43526. var iFace;
  43527. var iCorner = 0;
  43528. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  43529. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  43530. // note that if functionality to filter across the three texels for each corner, then
  43531. //indexed by corner and face idx. the array contains the face the start points belongs to.
  43532. var cornerPtr = [
  43533. [[], [], []],
  43534. [[], [], []],
  43535. [[], [], []],
  43536. [[], [], []],
  43537. [[], [], []],
  43538. [[], [], []],
  43539. [[], [], []],
  43540. [[], [], []]
  43541. ];
  43542. //if there is no fixup, or fixup width = 0, do nothing
  43543. if (cubeMapSize < 1) {
  43544. return;
  43545. }
  43546. //special case 1x1 cubemap, average face colors
  43547. if (cubeMapSize == 1) {
  43548. //iterate over channels
  43549. for (k = 0; k < this.numChannels; k++) {
  43550. var accum = 0.0;
  43551. //iterate over faces to accumulate face colors
  43552. for (iFace = 0; iFace < 6; iFace++) {
  43553. accum += cubeMap[iFace][k];
  43554. }
  43555. //compute average over 6 face colors
  43556. accum /= 6.0;
  43557. //iterate over faces to distribute face colors
  43558. for (iFace = 0; iFace < 6; iFace++) {
  43559. cubeMap[iFace][k] = accum;
  43560. }
  43561. }
  43562. return;
  43563. }
  43564. //iterate over faces to collect list of corner texel pointers
  43565. for (iFace = 0; iFace < 6; iFace++) {
  43566. //the 4 corner pointers for this face
  43567. faceCornerStartIndicies[0] = [iFace, 0];
  43568. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  43569. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  43570. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  43571. //iterate over face corners to collect cube corner pointers
  43572. for (iCorner = 0; iCorner < 4; iCorner++) {
  43573. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  43574. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  43575. cornerNumPtrs[corner]++;
  43576. }
  43577. }
  43578. //iterate over corners to average across corner tap values
  43579. for (iCorner = 0; iCorner < 8; iCorner++) {
  43580. for (k = 0; k < this.numChannels; k++) {
  43581. var cornerTapAccum = 0.0;
  43582. //iterate over corner texels and average results
  43583. for (i = 0; i < 3; i++) {
  43584. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  43585. }
  43586. //divide by 3 to compute average of corner tap values
  43587. cornerTapAccum *= (1.0 / 3.0);
  43588. //iterate over corner texels and average results
  43589. for (i = 0; i < 3; i++) {
  43590. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  43591. }
  43592. }
  43593. }
  43594. //iterate over the twelve edges of the cube to average across edges
  43595. for (i = 0; i < 12; i++) {
  43596. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  43597. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  43598. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  43599. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  43600. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  43601. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  43602. var edgeWalk = 0;
  43603. var neighborEdgeWalk = 0;
  43604. //Determine walking pointers based on edge type
  43605. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  43606. switch (edge) {
  43607. case PMREMGenerator.CP_EDGE_LEFT:
  43608. // no change to faceEdgeStartPtr
  43609. edgeWalk = this.numChannels * cubeMapSize;
  43610. break;
  43611. case PMREMGenerator.CP_EDGE_RIGHT:
  43612. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43613. edgeWalk = this.numChannels * cubeMapSize;
  43614. break;
  43615. case PMREMGenerator.CP_EDGE_TOP:
  43616. // no change to faceEdgeStartPtr
  43617. edgeWalk = this.numChannels;
  43618. break;
  43619. case PMREMGenerator.CP_EDGE_BOTTOM:
  43620. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43621. edgeWalk = this.numChannels;
  43622. break;
  43623. }
  43624. //For certain types of edge abutments, the neighbor edge walk needs to
  43625. // be flipped: the cases are
  43626. // if a left edge mates with a left or bottom edge on the neighbor
  43627. // if a top edge mates with a top or right edge on the neighbor
  43628. // if a right edge mates with a right or top edge on the neighbor
  43629. // if a bottom edge mates with a bottom or left edge on the neighbor
  43630. //Seeing as the edges are enumerated as follows
  43631. // left =0
  43632. // right =1
  43633. // top =2
  43634. // bottom =3
  43635. //
  43636. //If the edge enums are the same, or the sum of the enums == 3,
  43637. // the neighbor edge walk needs to be flipped
  43638. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  43639. switch (neighborEdge) {
  43640. case PMREMGenerator.CP_EDGE_LEFT:
  43641. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  43642. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43643. break;
  43644. case PMREMGenerator.CP_EDGE_RIGHT:
  43645. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43646. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43647. break;
  43648. case PMREMGenerator.CP_EDGE_TOP:
  43649. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43650. neighborEdgeWalk = -this.numChannels;
  43651. break;
  43652. case PMREMGenerator.CP_EDGE_BOTTOM:
  43653. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43654. neighborEdgeWalk = -this.numChannels;
  43655. break;
  43656. }
  43657. }
  43658. else {
  43659. //swapped direction neighbor edge walk
  43660. switch (neighborEdge) {
  43661. case PMREMGenerator.CP_EDGE_LEFT:
  43662. //no change to neighborEdgeStartPtr for this case since it points
  43663. // to the upper left corner already
  43664. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43665. break;
  43666. case PMREMGenerator.CP_EDGE_RIGHT:
  43667. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43668. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43669. break;
  43670. case PMREMGenerator.CP_EDGE_TOP:
  43671. //no change to neighborEdgeStartPtr for this case since it points
  43672. // to the upper left corner already
  43673. neighborEdgeWalk = this.numChannels;
  43674. break;
  43675. case PMREMGenerator.CP_EDGE_BOTTOM:
  43676. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43677. neighborEdgeWalk = this.numChannels;
  43678. break;
  43679. }
  43680. }
  43681. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  43682. //nearby neighborhood
  43683. //step ahead one texel on edge
  43684. edgeStartIndex += edgeWalk;
  43685. neighborEdgeStartIndex += neighborEdgeWalk;
  43686. // note that this loop does not process the corner texels, since they have already been
  43687. // averaged across faces across earlier
  43688. for (j = 1; j < (cubeMapSize - 1); j++) {
  43689. //for each set of taps along edge, average them
  43690. // and rewrite the results into the edges
  43691. for (k = 0; k < this.numChannels; k++) {
  43692. var edgeTap = cubeMap[face][edgeStartIndex + k];
  43693. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  43694. //compute average of tap intensity values
  43695. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  43696. //propagate average of taps to edge taps
  43697. cubeMap[face][edgeStartIndex + k] = avgTap;
  43698. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  43699. }
  43700. edgeStartIndex += edgeWalk;
  43701. neighborEdgeStartIndex += neighborEdgeWalk;
  43702. }
  43703. }
  43704. };
  43705. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  43706. PMREMGenerator.CP_UDIR = 0;
  43707. PMREMGenerator.CP_VDIR = 1;
  43708. PMREMGenerator.CP_FACEAXIS = 2;
  43709. //used to index cube faces
  43710. PMREMGenerator.CP_FACE_X_POS = 0;
  43711. PMREMGenerator.CP_FACE_X_NEG = 1;
  43712. PMREMGenerator.CP_FACE_Y_POS = 2;
  43713. PMREMGenerator.CP_FACE_Y_NEG = 3;
  43714. PMREMGenerator.CP_FACE_Z_POS = 4;
  43715. PMREMGenerator.CP_FACE_Z_NEG = 5;
  43716. //used to index image edges
  43717. // NOTE.. the actual number corresponding to the edge is important
  43718. // do not change these, or the code will break
  43719. //
  43720. // CP_EDGE_LEFT is u = 0
  43721. // CP_EDGE_RIGHT is u = width-1
  43722. // CP_EDGE_TOP is v = 0
  43723. // CP_EDGE_BOTTOM is v = height-1
  43724. PMREMGenerator.CP_EDGE_LEFT = 0;
  43725. PMREMGenerator.CP_EDGE_RIGHT = 1;
  43726. PMREMGenerator.CP_EDGE_TOP = 2;
  43727. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  43728. //corners of CUBE map (P or N specifys if it corresponds to the
  43729. // positive or negative direction each of X, Y, and Z
  43730. PMREMGenerator.CP_CORNER_NNN = 0;
  43731. PMREMGenerator.CP_CORNER_NNP = 1;
  43732. PMREMGenerator.CP_CORNER_NPN = 2;
  43733. PMREMGenerator.CP_CORNER_NPP = 3;
  43734. PMREMGenerator.CP_CORNER_PNN = 4;
  43735. PMREMGenerator.CP_CORNER_PNP = 5;
  43736. PMREMGenerator.CP_CORNER_PPN = 6;
  43737. PMREMGenerator.CP_CORNER_PPP = 7;
  43738. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  43739. //3x2 matrices that map cube map indexing vectors in 3d
  43740. // (after face selection and divide through by the
  43741. // _ABSOLUTE VALUE_ of the max coord)
  43742. // into NVC space
  43743. //Note this currently assumes the D3D cube face ordering and orientation
  43744. PMREMGenerator._sgFace2DMapping = [
  43745. //XPOS face
  43746. [[0, 0, -1],
  43747. [0, -1, 0],
  43748. [1, 0, 0]],
  43749. //XNEG face
  43750. [[0, 0, 1],
  43751. [0, -1, 0],
  43752. [-1, 0, 0]],
  43753. //YPOS face
  43754. [[1, 0, 0],
  43755. [0, 0, 1],
  43756. [0, 1, 0]],
  43757. //YNEG face
  43758. [[1, 0, 0],
  43759. [0, 0, -1],
  43760. [0, -1, 0]],
  43761. //ZPOS face
  43762. [[1, 0, 0],
  43763. [0, -1, 0],
  43764. [0, 0, 1]],
  43765. //ZNEG face
  43766. [[-1, 0, 0],
  43767. [0, -1, 0],
  43768. [0, 0, -1]],
  43769. ];
  43770. //------------------------------------------------------------------------------
  43771. // D3D cube map face specification
  43772. // mapping from 3D x,y,z cube map lookup coordinates
  43773. // to 2D within face u,v coordinates
  43774. //
  43775. // --------------------> U direction
  43776. // | (within-face texture space)
  43777. // | _____
  43778. // | | |
  43779. // | | +Y |
  43780. // | _____|_____|_____ _____
  43781. // | | | | | |
  43782. // | | -X | +Z | +X | -Z |
  43783. // | |_____|_____|_____|_____|
  43784. // | | |
  43785. // | | -Y |
  43786. // | |_____|
  43787. // |
  43788. // v V direction
  43789. // (within-face texture space)
  43790. //------------------------------------------------------------------------------
  43791. //Information about neighbors and how texture coorrdinates change across faces
  43792. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  43793. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  43794. //Note this currently assumes the D3D cube face ordering and orientation
  43795. PMREMGenerator._sgCubeNgh = [
  43796. //XPOS face
  43797. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43798. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43799. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43800. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  43801. //XNEG face
  43802. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43803. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  43804. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  43805. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  43806. //YPOS face
  43807. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43808. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43809. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43810. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  43811. //YNEG face
  43812. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43813. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43814. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43815. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  43816. //ZPOS face
  43817. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43818. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43819. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43820. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  43821. //ZNEG face
  43822. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43823. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43824. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  43825. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  43826. ];
  43827. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  43828. // this table is used to average over the edges.
  43829. PMREMGenerator._sgCubeEdgeList = [
  43830. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43831. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43832. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43833. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43834. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43835. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43836. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43837. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43838. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  43839. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43840. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43841. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  43842. ];
  43843. //Information about which of the 8 cube corners are correspond to the
  43844. // the 4 corners in each cube face
  43845. // the order is upper left, upper right, lower left, lower right
  43846. PMREMGenerator._sgCubeCornerList = [
  43847. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  43848. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  43849. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  43850. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  43851. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  43852. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  43853. ];
  43854. return PMREMGenerator;
  43855. })();
  43856. Internals.PMREMGenerator = PMREMGenerator;
  43857. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43858. })(BABYLON || (BABYLON = {}));
  43859. var BABYLON;
  43860. (function (BABYLON) {
  43861. /**
  43862. * This represents a texture coming from an HDR input.
  43863. *
  43864. * The only supported format is currently panorama picture stored in RGBE format.
  43865. * Example of such files can be found on HDRLib: http://hdrlib.com/
  43866. */
  43867. var HDRCubeTexture = (function (_super) {
  43868. __extends(HDRCubeTexture, _super);
  43869. /**
  43870. * Instantiates an HDRTexture from the following parameters.
  43871. *
  43872. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  43873. * @param scene The scene the texture will be used in
  43874. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  43875. * @param noMipmap Forces to not generate the mipmap if true
  43876. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  43877. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  43878. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  43879. */
  43880. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  43881. if (noMipmap === void 0) { noMipmap = false; }
  43882. if (generateHarmonics === void 0) { generateHarmonics = true; }
  43883. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  43884. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  43885. _super.call(this, scene);
  43886. this._useInGammaSpace = false;
  43887. this._generateHarmonics = true;
  43888. this._isBABYLONPreprocessed = false;
  43889. /**
  43890. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  43891. */
  43892. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  43893. /**
  43894. * The spherical polynomial data extracted from the texture.
  43895. */
  43896. this.sphericalPolynomial = null;
  43897. /**
  43898. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  43899. * This is usefull at run time to apply the good shader.
  43900. */
  43901. this.isPMREM = false;
  43902. if (!url) {
  43903. return;
  43904. }
  43905. this.name = url;
  43906. this.url = url;
  43907. this.hasAlpha = false;
  43908. this.isCube = true;
  43909. this._textureMatrix = BABYLON.Matrix.Identity();
  43910. if (size) {
  43911. this._isBABYLONPreprocessed = false;
  43912. this._noMipmap = noMipmap;
  43913. this._size = size;
  43914. this._useInGammaSpace = useInGammaSpace;
  43915. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  43916. }
  43917. else {
  43918. this._isBABYLONPreprocessed = true;
  43919. this._noMipmap = false;
  43920. this._useInGammaSpace = false;
  43921. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD;
  43922. }
  43923. this.isPMREM = this._usePMREMGenerator;
  43924. this._texture = this._getFromCache(url, this._noMipmap);
  43925. if (!this._texture) {
  43926. if (!scene.useDelayedTextureLoading) {
  43927. this.loadTexture();
  43928. }
  43929. else {
  43930. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43931. }
  43932. }
  43933. }
  43934. /**
  43935. * Occurs when the file is a preprocessed .babylon.hdr file.
  43936. */
  43937. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  43938. var _this = this;
  43939. var mipLevels = 0;
  43940. var floatArrayView = null;
  43941. var mipmapGenerator = function (data) {
  43942. var mips = [];
  43943. var startIndex = 30;
  43944. for (var level = 0; level < mipLevels; level++) {
  43945. mips.push([]);
  43946. // Fill each pixel of the mip level.
  43947. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  43948. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43949. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  43950. mips[level].push(faceData);
  43951. startIndex += faceSize;
  43952. }
  43953. }
  43954. return mips;
  43955. };
  43956. var callback = function (buffer) {
  43957. // Create Native Array Views
  43958. var intArrayView = new Int32Array(buffer);
  43959. floatArrayView = new Float32Array(buffer);
  43960. // Fill header.
  43961. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  43962. _this._size = intArrayView[1]; // CubeMap max mip face size.
  43963. // Update Texture Information.
  43964. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  43965. // Fill polynomial information.
  43966. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  43967. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  43968. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  43969. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  43970. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  43971. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  43972. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  43973. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  43974. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  43975. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  43976. // Fill pixel data.
  43977. mipLevels = intArrayView[29]; // Number of mip levels.
  43978. var startIndex = 30;
  43979. var data = [];
  43980. var faceSize = Math.pow(_this._size, 2) * 3;
  43981. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43982. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  43983. }
  43984. var results = [];
  43985. var byteArray = null;
  43986. // Create uintarray fallback.
  43987. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  43988. // 3 channels of 1 bytes per pixel in bytes.
  43989. var byteBuffer = new ArrayBuffer(faceSize);
  43990. byteArray = new Uint8Array(byteBuffer);
  43991. mipmapGenerator = null;
  43992. }
  43993. // Push each faces.
  43994. for (var j = 0; j < 6; j++) {
  43995. var dataFace = data[j];
  43996. // If special cases.
  43997. if (_this._useInGammaSpace || byteArray) {
  43998. for (var i = 0; i < _this._size * _this._size; i++) {
  43999. // Put in gamma space if requested.
  44000. if (_this._useInGammaSpace) {
  44001. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  44002. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  44003. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  44004. }
  44005. // Convert to int texture for fallback.
  44006. if (byteArray) {
  44007. // R
  44008. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  44009. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  44010. // G
  44011. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  44012. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  44013. // B
  44014. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  44015. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  44016. }
  44017. }
  44018. }
  44019. results.push(dataFace);
  44020. }
  44021. return results;
  44022. };
  44023. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  44024. };
  44025. /**
  44026. * Occurs when the file is raw .hdr file.
  44027. */
  44028. HDRCubeTexture.prototype.loadHDRTexture = function () {
  44029. var _this = this;
  44030. var callback = function (buffer) {
  44031. // Extract the raw linear data.
  44032. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  44033. // Generate harmonics if needed.
  44034. if (_this._generateHarmonics) {
  44035. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  44036. }
  44037. var results = [];
  44038. var byteArray = null;
  44039. // Create uintarray fallback.
  44040. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  44041. // 3 channels of 1 bytes per pixel in bytes.
  44042. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  44043. byteArray = new Uint8Array(byteBuffer);
  44044. }
  44045. // Push each faces.
  44046. for (var j = 0; j < 6; j++) {
  44047. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  44048. // If special cases.
  44049. if (_this._useInGammaSpace || byteArray) {
  44050. for (var i = 0; i < _this._size * _this._size; i++) {
  44051. // Put in gamma space if requested.
  44052. if (_this._useInGammaSpace) {
  44053. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  44054. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  44055. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  44056. }
  44057. // Convert to int texture for fallback.
  44058. if (byteArray) {
  44059. // R
  44060. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  44061. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  44062. // G
  44063. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  44064. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  44065. // B
  44066. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  44067. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  44068. }
  44069. }
  44070. }
  44071. results.push(dataFace);
  44072. }
  44073. return results;
  44074. };
  44075. var mipmapGenerator = null;
  44076. if (!this._noMipmap && this._usePMREMGenerator) {
  44077. mipmapGenerator = function (data) {
  44078. // Custom setup of the generator matching with the PBR shader values.
  44079. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  44080. return generator.filterCubeMap();
  44081. };
  44082. }
  44083. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  44084. };
  44085. /**
  44086. * Starts the loading process of the texture.
  44087. */
  44088. HDRCubeTexture.prototype.loadTexture = function () {
  44089. if (this._isBABYLONPreprocessed) {
  44090. this.loadBabylonTexture();
  44091. }
  44092. else {
  44093. this.loadHDRTexture();
  44094. }
  44095. };
  44096. HDRCubeTexture.prototype.clone = function () {
  44097. var size = this._isBABYLONPreprocessed ? null : this._size;
  44098. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  44099. // Base texture
  44100. newTexture.level = this.level;
  44101. newTexture.wrapU = this.wrapU;
  44102. newTexture.wrapV = this.wrapV;
  44103. newTexture.coordinatesIndex = this.coordinatesIndex;
  44104. newTexture.coordinatesMode = this.coordinatesMode;
  44105. return newTexture;
  44106. };
  44107. // Methods
  44108. HDRCubeTexture.prototype.delayLoad = function () {
  44109. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  44110. return;
  44111. }
  44112. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  44113. this._texture = this._getFromCache(this.url, this._noMipmap);
  44114. if (!this._texture) {
  44115. this.loadTexture();
  44116. }
  44117. };
  44118. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  44119. return this._textureMatrix;
  44120. };
  44121. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  44122. var texture = null;
  44123. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  44124. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  44125. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  44126. texture.name = parsedTexture.name;
  44127. texture.hasAlpha = parsedTexture.hasAlpha;
  44128. texture.level = parsedTexture.level;
  44129. texture.coordinatesMode = parsedTexture.coordinatesMode;
  44130. }
  44131. return texture;
  44132. };
  44133. HDRCubeTexture.prototype.serialize = function () {
  44134. if (!this.name) {
  44135. return null;
  44136. }
  44137. var serializationObject = {};
  44138. serializationObject.name = this.name;
  44139. serializationObject.hasAlpha = this.hasAlpha;
  44140. serializationObject.isCube = true;
  44141. serializationObject.level = this.level;
  44142. serializationObject.size = this._size;
  44143. serializationObject.coordinatesMode = this.coordinatesMode;
  44144. serializationObject.useInGammaSpace = this._useInGammaSpace;
  44145. serializationObject.generateHarmonics = this._generateHarmonics;
  44146. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  44147. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  44148. return serializationObject;
  44149. };
  44150. /**
  44151. * Saves as a file the data contained in the texture in a binary format.
  44152. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  44153. * as the spherical used in the lighting.
  44154. * @param url The HDR file url.
  44155. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  44156. * @param onError Method called if any error happens during download.
  44157. * @return The packed binary data.
  44158. */
  44159. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  44160. if (onError === void 0) { onError = null; }
  44161. var callback = function (buffer) {
  44162. var data = new Blob([buffer], { type: 'application/octet-stream' });
  44163. // Returns a URL you can use as a href.
  44164. var objUrl = window.URL.createObjectURL(data);
  44165. // Simulates a link to it and click to dowload.
  44166. var a = document.createElement("a");
  44167. document.body.appendChild(a);
  44168. a.style.display = "none";
  44169. a.href = objUrl;
  44170. a.download = "envmap.babylon.hdr";
  44171. a.click();
  44172. };
  44173. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  44174. };
  44175. /**
  44176. * Serializes the data contained in the texture in a binary format.
  44177. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  44178. * as the spherical used in the lighting.
  44179. * @param url The HDR file url.
  44180. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  44181. * @param onError Method called if any error happens during download.
  44182. * @return The packed binary data.
  44183. */
  44184. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  44185. if (onError === void 0) { onError = null; }
  44186. // Needs the url tho create the texture.
  44187. if (!url) {
  44188. return null;
  44189. }
  44190. // Check Power of two size.
  44191. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  44192. return null;
  44193. }
  44194. var getDataCallback = function (dataBuffer) {
  44195. // Extract the raw linear data.
  44196. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  44197. // Generate harmonics if needed.
  44198. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  44199. // Generate seamless faces
  44200. var mipGeneratorArray = [];
  44201. // Data are known to be in +X +Y +Z -X -Y -Z
  44202. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  44203. mipGeneratorArray.push(cubeData.right); // +X
  44204. mipGeneratorArray.push(cubeData.left); // -X
  44205. mipGeneratorArray.push(cubeData.up); // +Y
  44206. mipGeneratorArray.push(cubeData.down); // -Y
  44207. mipGeneratorArray.push(cubeData.front); // +Z
  44208. mipGeneratorArray.push(cubeData.back); // -Z
  44209. // Custom setup of the generator matching with the PBR shader values.
  44210. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  44211. var mippedData = generator.filterCubeMap();
  44212. // Compute required byte length.
  44213. var byteLength = 1 * 4; // Raw Data Version int32.
  44214. byteLength += 4; // CubeMap max mip face size int32.
  44215. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  44216. // Add data size.
  44217. byteLength += 4; // Number of mip levels int32.
  44218. for (var level = 0; level < mippedData.length; level++) {
  44219. var mipSize = size >> level;
  44220. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  44221. }
  44222. // Prepare binary structure.
  44223. var buffer = new ArrayBuffer(byteLength);
  44224. var intArrayView = new Int32Array(buffer);
  44225. var floatArrayView = new Float32Array(buffer);
  44226. // Fill header.
  44227. intArrayView[0] = 1; // Version 1.
  44228. intArrayView[1] = size; // CubeMap max mip face size.
  44229. // Fill polynomial information.
  44230. sphericalPolynomial.x.toArray(floatArrayView, 2);
  44231. sphericalPolynomial.y.toArray(floatArrayView, 5);
  44232. sphericalPolynomial.z.toArray(floatArrayView, 8);
  44233. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  44234. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  44235. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  44236. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  44237. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  44238. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  44239. // Fill pixel data.
  44240. intArrayView[29] = mippedData.length; // Number of mip levels.
  44241. var startIndex = 30;
  44242. for (var level = 0; level < mippedData.length; level++) {
  44243. // Fill each pixel of the mip level.
  44244. var faceSize = Math.pow(size >> level, 2) * 3;
  44245. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44246. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  44247. startIndex += faceSize;
  44248. }
  44249. }
  44250. // Callback.
  44251. callback(buffer);
  44252. };
  44253. // Download and process.
  44254. BABYLON.Tools.LoadFile(url, function (data) {
  44255. getDataCallback(data);
  44256. }, null, null, true, onError);
  44257. };
  44258. HDRCubeTexture._facesMapping = [
  44259. "right",
  44260. "up",
  44261. "front",
  44262. "left",
  44263. "down",
  44264. "back"
  44265. ];
  44266. return HDRCubeTexture;
  44267. })(BABYLON.BaseTexture);
  44268. BABYLON.HDRCubeTexture = HDRCubeTexture;
  44269. })(BABYLON || (BABYLON = {}));
  44270. var BABYLON;
  44271. (function (BABYLON) {
  44272. var Debug;
  44273. (function (Debug) {
  44274. /**
  44275. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  44276. */
  44277. var SkeletonViewer = (function () {
  44278. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  44279. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  44280. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  44281. this.skeleton = skeleton;
  44282. this.mesh = mesh;
  44283. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  44284. this.renderingGroupId = renderingGroupId;
  44285. this.color = BABYLON.Color3.White();
  44286. this._debugLines = [];
  44287. this._isEnabled = false;
  44288. this._scene = scene;
  44289. this.update();
  44290. this._renderFunction = this.update.bind(this);
  44291. }
  44292. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  44293. get: function () {
  44294. return this._isEnabled;
  44295. },
  44296. set: function (value) {
  44297. if (this._isEnabled === value) {
  44298. return;
  44299. }
  44300. this._isEnabled = value;
  44301. if (value) {
  44302. this._scene.registerBeforeRender(this._renderFunction);
  44303. }
  44304. else {
  44305. this._scene.unregisterBeforeRender(this._renderFunction);
  44306. }
  44307. },
  44308. enumerable: true,
  44309. configurable: true
  44310. });
  44311. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  44312. if (x === void 0) { x = 0; }
  44313. if (y === void 0) { y = 0; }
  44314. if (z === void 0) { z = 0; }
  44315. var tmat = BABYLON.Tmp.Matrix[0];
  44316. var parentBone = bone.getParent();
  44317. tmat.copyFrom(bone.getLocalMatrix());
  44318. if (x !== 0 || y !== 0 || z !== 0) {
  44319. var tmat2 = BABYLON.Tmp.Matrix[1];
  44320. BABYLON.Matrix.IdentityToRef(tmat2);
  44321. tmat2.m[12] = x;
  44322. tmat2.m[13] = y;
  44323. tmat2.m[14] = z;
  44324. tmat2.multiplyToRef(tmat, tmat);
  44325. }
  44326. if (parentBone) {
  44327. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  44328. }
  44329. tmat.multiplyToRef(meshMat, tmat);
  44330. position.x = tmat.m[12];
  44331. position.y = tmat.m[13];
  44332. position.z = tmat.m[14];
  44333. };
  44334. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  44335. var len = bones.length;
  44336. for (var i = 0; i < len; i++) {
  44337. var bone = bones[i];
  44338. var points = this._debugLines[i];
  44339. if (!points) {
  44340. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44341. this._debugLines[i] = points;
  44342. }
  44343. this._getBonePosition(points[0], bone, meshMat);
  44344. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  44345. }
  44346. };
  44347. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  44348. var len = bones.length;
  44349. var boneNum = 0;
  44350. for (var i = len - 1; i >= 0; i--) {
  44351. var childBone = bones[i];
  44352. var parentBone = childBone.getParent();
  44353. if (!parentBone) {
  44354. continue;
  44355. }
  44356. var points = this._debugLines[boneNum];
  44357. if (!points) {
  44358. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44359. this._debugLines[boneNum] = points;
  44360. }
  44361. this._getBonePosition(points[0], childBone, meshMat);
  44362. this._getBonePosition(points[1], parentBone, meshMat);
  44363. boneNum++;
  44364. }
  44365. };
  44366. SkeletonViewer.prototype.update = function () {
  44367. if (this.autoUpdateBonesMatrices) {
  44368. this._updateBoneMatrix(this.skeleton.bones[0]);
  44369. }
  44370. if (this.skeleton.bones[0].length === undefined) {
  44371. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44372. }
  44373. else {
  44374. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44375. }
  44376. if (!this._debugMesh) {
  44377. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  44378. this._debugMesh.renderingGroupId = this.renderingGroupId;
  44379. }
  44380. else {
  44381. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  44382. }
  44383. this._debugMesh.color = this.color;
  44384. };
  44385. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  44386. if (bone.getParent()) {
  44387. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  44388. }
  44389. var children = bone.children;
  44390. var len = children.length;
  44391. for (var i = 0; i < len; i++) {
  44392. this._updateBoneMatrix(children[i]);
  44393. }
  44394. };
  44395. SkeletonViewer.prototype.dispose = function () {
  44396. if (this._debugMesh) {
  44397. this.isEnabled = false;
  44398. this._debugMesh.dispose();
  44399. this._debugMesh = null;
  44400. }
  44401. };
  44402. return SkeletonViewer;
  44403. })();
  44404. Debug.SkeletonViewer = SkeletonViewer;
  44405. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44406. })(BABYLON || (BABYLON = {}));
  44407. var BABYLON;
  44408. (function (BABYLON) {
  44409. var maxSimultaneousLights = 4;
  44410. var PBRMaterialDefines = (function (_super) {
  44411. __extends(PBRMaterialDefines, _super);
  44412. function PBRMaterialDefines() {
  44413. _super.call(this);
  44414. this.ALBEDO = false;
  44415. this.AMBIENT = false;
  44416. this.OPACITY = false;
  44417. this.OPACITYRGB = false;
  44418. this.REFLECTION = false;
  44419. this.EMISSIVE = false;
  44420. this.REFLECTIVITY = false;
  44421. this.BUMP = false;
  44422. this.PARALLAX = false;
  44423. this.PARALLAXOCCLUSION = false;
  44424. this.SPECULAROVERALPHA = false;
  44425. this.CLIPPLANE = false;
  44426. this.ALPHATEST = false;
  44427. this.ALPHAFROMALBEDO = false;
  44428. this.POINTSIZE = false;
  44429. this.FOG = false;
  44430. this.LIGHT0 = false;
  44431. this.LIGHT1 = false;
  44432. this.LIGHT2 = false;
  44433. this.LIGHT3 = false;
  44434. this.SPOTLIGHT0 = false;
  44435. this.SPOTLIGHT1 = false;
  44436. this.SPOTLIGHT2 = false;
  44437. this.SPOTLIGHT3 = false;
  44438. this.HEMILIGHT0 = false;
  44439. this.HEMILIGHT1 = false;
  44440. this.HEMILIGHT2 = false;
  44441. this.HEMILIGHT3 = false;
  44442. this.POINTLIGHT0 = false;
  44443. this.POINTLIGHT1 = false;
  44444. this.POINTLIGHT2 = false;
  44445. this.POINTLIGHT3 = false;
  44446. this.DIRLIGHT0 = false;
  44447. this.DIRLIGHT1 = false;
  44448. this.DIRLIGHT2 = false;
  44449. this.DIRLIGHT3 = false;
  44450. this.SPECULARTERM = false;
  44451. this.SHADOW0 = false;
  44452. this.SHADOW1 = false;
  44453. this.SHADOW2 = false;
  44454. this.SHADOW3 = false;
  44455. this.SHADOWS = false;
  44456. this.SHADOWVSM0 = false;
  44457. this.SHADOWVSM1 = false;
  44458. this.SHADOWVSM2 = false;
  44459. this.SHADOWVSM3 = false;
  44460. this.SHADOWPCF0 = false;
  44461. this.SHADOWPCF1 = false;
  44462. this.SHADOWPCF2 = false;
  44463. this.SHADOWPCF3 = false;
  44464. this.OPACITYFRESNEL = false;
  44465. this.EMISSIVEFRESNEL = false;
  44466. this.FRESNEL = false;
  44467. this.NORMAL = false;
  44468. this.UV1 = false;
  44469. this.UV2 = false;
  44470. this.VERTEXCOLOR = false;
  44471. this.VERTEXALPHA = false;
  44472. this.NUM_BONE_INFLUENCERS = 0;
  44473. this.BonesPerMesh = 0;
  44474. this.INSTANCES = false;
  44475. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44476. this.MICROSURFACEAUTOMATIC = false;
  44477. this.EMISSIVEASILLUMINATION = false;
  44478. this.LINKEMISSIVEWITHALBEDO = false;
  44479. this.LIGHTMAP = false;
  44480. this.USELIGHTMAPASSHADOWMAP = false;
  44481. this.REFLECTIONMAP_3D = false;
  44482. this.REFLECTIONMAP_SPHERICAL = false;
  44483. this.REFLECTIONMAP_PLANAR = false;
  44484. this.REFLECTIONMAP_CUBIC = false;
  44485. this.REFLECTIONMAP_PROJECTION = false;
  44486. this.REFLECTIONMAP_SKYBOX = false;
  44487. this.REFLECTIONMAP_EXPLICIT = false;
  44488. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44489. this.INVERTCUBICMAP = false;
  44490. this.LOGARITHMICDEPTH = false;
  44491. this.CAMERATONEMAP = false;
  44492. this.CAMERACONTRAST = false;
  44493. this.OVERLOADEDVALUES = false;
  44494. this.OVERLOADEDSHADOWVALUES = false;
  44495. this.USESPHERICALFROMREFLECTIONMAP = false;
  44496. this.REFRACTION = false;
  44497. this.REFRACTIONMAP_3D = false;
  44498. this.LINKREFRACTIONTOTRANSPARENCY = false;
  44499. this.REFRACTIONMAPINLINEARSPACE = false;
  44500. this.LODBASEDMICROSFURACE = false;
  44501. this.USEPHYSICALLIGHTFALLOFF = false;
  44502. this.RADIANCEOVERALPHA = false;
  44503. this.USEPMREMREFLECTION = false;
  44504. this.USEPMREMREFRACTION = false;
  44505. this._keys = Object.keys(this);
  44506. }
  44507. return PBRMaterialDefines;
  44508. })(BABYLON.MaterialDefines);
  44509. /**
  44510. * The Physically based material of BJS.
  44511. *
  44512. * This offers the main features of a standard PBR material.
  44513. * For more information, please refer to the documentation :
  44514. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44515. */
  44516. var PBRMaterial = (function (_super) {
  44517. __extends(PBRMaterial, _super);
  44518. /**
  44519. * Instantiates a new PBRMaterial instance.
  44520. *
  44521. * @param name The material name
  44522. * @param scene The scene the material will be use in.
  44523. */
  44524. function PBRMaterial(name, scene) {
  44525. var _this = this;
  44526. _super.call(this, name, scene);
  44527. /**
  44528. * Intensity of the direct lights e.g. the four lights available in your scene.
  44529. * This impacts both the direct diffuse and specular highlights.
  44530. */
  44531. this.directIntensity = 1.0;
  44532. /**
  44533. * Intensity of the emissive part of the material.
  44534. * This helps controlling the emissive effect without modifying the emissive color.
  44535. */
  44536. this.emissiveIntensity = 1.0;
  44537. /**
  44538. * Intensity of the environment e.g. how much the environment will light the object
  44539. * either through harmonics for rough material or through the refelction for shiny ones.
  44540. */
  44541. this.environmentIntensity = 1.0;
  44542. /**
  44543. * This is a special control allowing the reduction of the specular highlights coming from the
  44544. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44545. */
  44546. this.specularIntensity = 1.0;
  44547. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  44548. /**
  44549. * Debug Control allowing disabling the bump map on this material.
  44550. */
  44551. this.disableBumpMap = false;
  44552. /**
  44553. * Debug Control helping enforcing or dropping the darkness of shadows.
  44554. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  44555. */
  44556. this.overloadedShadowIntensity = 1.0;
  44557. /**
  44558. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  44559. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  44560. */
  44561. this.overloadedShadeIntensity = 1.0;
  44562. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  44563. /**
  44564. * The camera exposure used on this material.
  44565. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44566. * This corresponds to a photographic exposure.
  44567. */
  44568. this.cameraExposure = 1.0;
  44569. /**
  44570. * The camera contrast used on this material.
  44571. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  44572. */
  44573. this.cameraContrast = 1.0;
  44574. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  44575. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  44576. /**
  44577. * Debug Control allowing to overload the ambient color.
  44578. * This as to be use with the overloadedAmbientIntensity parameter.
  44579. */
  44580. this.overloadedAmbient = BABYLON.Color3.White();
  44581. /**
  44582. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  44583. */
  44584. this.overloadedAmbientIntensity = 0.0;
  44585. /**
  44586. * Debug Control allowing to overload the albedo color.
  44587. * This as to be use with the overloadedAlbedoIntensity parameter.
  44588. */
  44589. this.overloadedAlbedo = BABYLON.Color3.White();
  44590. /**
  44591. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  44592. */
  44593. this.overloadedAlbedoIntensity = 0.0;
  44594. /**
  44595. * Debug Control allowing to overload the reflectivity color.
  44596. * This as to be use with the overloadedReflectivityIntensity parameter.
  44597. */
  44598. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  44599. /**
  44600. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  44601. */
  44602. this.overloadedReflectivityIntensity = 0.0;
  44603. /**
  44604. * Debug Control allowing to overload the emissive color.
  44605. * This as to be use with the overloadedEmissiveIntensity parameter.
  44606. */
  44607. this.overloadedEmissive = BABYLON.Color3.White();
  44608. /**
  44609. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  44610. */
  44611. this.overloadedEmissiveIntensity = 0.0;
  44612. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  44613. /**
  44614. * Debug Control allowing to overload the reflection color.
  44615. * This as to be use with the overloadedReflectionIntensity parameter.
  44616. */
  44617. this.overloadedReflection = BABYLON.Color3.White();
  44618. /**
  44619. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  44620. */
  44621. this.overloadedReflectionIntensity = 0.0;
  44622. /**
  44623. * Debug Control allowing to overload the microsurface.
  44624. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  44625. */
  44626. this.overloadedMicroSurface = 0.0;
  44627. /**
  44628. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  44629. */
  44630. this.overloadedMicroSurfaceIntensity = 0.0;
  44631. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  44632. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44633. /**
  44634. * AKA Diffuse Color in other nomenclature.
  44635. */
  44636. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44637. /**
  44638. * AKA Specular Color in other nomenclature.
  44639. */
  44640. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44641. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  44642. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44643. /**
  44644. * AKA Glossiness in other nomenclature.
  44645. */
  44646. this.microSurface = 0.9;
  44647. /**
  44648. * source material index of refraction (IOR)' / 'destination material IOR.
  44649. */
  44650. this.indexOfRefraction = 0.66;
  44651. /**
  44652. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44653. */
  44654. this.invertRefractionY = false;
  44655. /**
  44656. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44657. * Materials half opaque for instance using refraction could benefit from this control.
  44658. */
  44659. this.linkRefractionWithTransparency = false;
  44660. /**
  44661. * The emissive and albedo are linked to never be more than one (Energy conservation).
  44662. */
  44663. this.linkEmissiveWithAlbedo = false;
  44664. this.useLightmapAsShadowmap = false;
  44665. /**
  44666. * In this mode, the emissive informtaion will always be added to the lighting once.
  44667. * A light for instance can be thought as emissive.
  44668. */
  44669. this.useEmissiveAsIllumination = false;
  44670. /**
  44671. * Secifies that the alpha is coming form the albedo channel alpha channel.
  44672. */
  44673. this.useAlphaFromAlbedoTexture = false;
  44674. /**
  44675. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44676. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44677. */
  44678. this.useSpecularOverAlpha = true;
  44679. /**
  44680. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44681. */
  44682. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44683. /**
  44684. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44685. * The material will try to infer what glossiness each pixel should be.
  44686. */
  44687. this.useAutoMicroSurfaceFromReflectivityMap = false;
  44688. /**
  44689. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  44690. * the creation of the material.
  44691. */
  44692. this.useScalarInLinearSpace = false;
  44693. /**
  44694. * BJS is using an harcoded light falloff based on a manually sets up range.
  44695. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44696. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44697. */
  44698. this.usePhysicalLightFalloff = true;
  44699. /**
  44700. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44701. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44702. */
  44703. this.useRadianceOverAlpha = true;
  44704. /**
  44705. * Allows using the bump map in parallax mode.
  44706. */
  44707. this.useParallax = false;
  44708. /**
  44709. * Allows using the bump map in parallax occlusion mode.
  44710. */
  44711. this.useParallaxOcclusion = false;
  44712. /**
  44713. * Controls the scale bias of the parallax mode.
  44714. */
  44715. this.parallaxScaleBias = 0.05;
  44716. this.disableLighting = false;
  44717. this._renderTargets = new BABYLON.SmartArray(16);
  44718. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44719. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44720. this._tempColor = new BABYLON.Color3();
  44721. this._defines = new PBRMaterialDefines();
  44722. this._cachedDefines = new PBRMaterialDefines();
  44723. this._myScene = null;
  44724. this._myShadowGenerator = null;
  44725. this._cachedDefines.BonesPerMesh = -1;
  44726. this.getRenderTargetTextures = function () {
  44727. _this._renderTargets.reset();
  44728. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  44729. _this._renderTargets.push(_this.reflectionTexture);
  44730. }
  44731. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  44732. _this._renderTargets.push(_this.refractionTexture);
  44733. }
  44734. return _this._renderTargets;
  44735. };
  44736. }
  44737. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  44738. get: function () {
  44739. return this._useLogarithmicDepth;
  44740. },
  44741. set: function (value) {
  44742. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44743. },
  44744. enumerable: true,
  44745. configurable: true
  44746. });
  44747. PBRMaterial.prototype.needAlphaBlending = function () {
  44748. if (this.linkRefractionWithTransparency) {
  44749. return false;
  44750. }
  44751. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  44752. };
  44753. PBRMaterial.prototype.needAlphaTesting = function () {
  44754. if (this.linkRefractionWithTransparency) {
  44755. return false;
  44756. }
  44757. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  44758. };
  44759. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44760. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  44761. };
  44762. PBRMaterial.prototype.getAlphaTestTexture = function () {
  44763. return this.albedoTexture;
  44764. };
  44765. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44766. if (!mesh) {
  44767. return true;
  44768. }
  44769. if (this._defines.INSTANCES !== useInstances) {
  44770. return false;
  44771. }
  44772. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  44773. return true;
  44774. }
  44775. return false;
  44776. };
  44777. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  44778. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  44779. };
  44780. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  44781. if (!useScalarInLinear) {
  44782. color.toLinearSpaceToRef(ref);
  44783. }
  44784. else {
  44785. ref.r = color.r;
  44786. ref.g = color.g;
  44787. ref.b = color.b;
  44788. }
  44789. };
  44790. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  44791. var lightIndex = 0;
  44792. var depthValuesAlreadySet = false;
  44793. for (var index = 0; index < scene.lights.length; index++) {
  44794. var light = scene.lights[index];
  44795. if (!light.isEnabled()) {
  44796. continue;
  44797. }
  44798. if (!light.canAffectMesh(mesh)) {
  44799. continue;
  44800. }
  44801. this._lightRadiuses[lightIndex] = light.radius;
  44802. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  44803. // GAMMA CORRECTION.
  44804. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  44805. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  44806. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  44807. if (defines["SPECULARTERM"]) {
  44808. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  44809. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  44810. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  44811. }
  44812. // Shadows
  44813. if (scene.shadowsEnabled) {
  44814. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  44815. }
  44816. lightIndex++;
  44817. if (lightIndex === maxSimultaneousLights)
  44818. break;
  44819. }
  44820. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  44821. };
  44822. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  44823. if (this.checkReadyOnlyOnce) {
  44824. if (this._wasPreviouslyReady) {
  44825. return true;
  44826. }
  44827. }
  44828. var scene = this.getScene();
  44829. if (!this.checkReadyOnEveryCall) {
  44830. if (this._renderId === scene.getRenderId()) {
  44831. if (this._checkCache(scene, mesh, useInstances)) {
  44832. return true;
  44833. }
  44834. }
  44835. }
  44836. var engine = scene.getEngine();
  44837. var needNormals = false;
  44838. var needUVs = false;
  44839. this._defines.reset();
  44840. if (scene.texturesEnabled) {
  44841. // Textures
  44842. if (scene.texturesEnabled) {
  44843. if (scene.getEngine().getCaps().textureLOD) {
  44844. this._defines.LODBASEDMICROSFURACE = true;
  44845. }
  44846. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44847. if (!this.albedoTexture.isReady()) {
  44848. return false;
  44849. }
  44850. else {
  44851. needUVs = true;
  44852. this._defines.ALBEDO = true;
  44853. }
  44854. }
  44855. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44856. if (!this.ambientTexture.isReady()) {
  44857. return false;
  44858. }
  44859. else {
  44860. needUVs = true;
  44861. this._defines.AMBIENT = true;
  44862. }
  44863. }
  44864. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44865. if (!this.opacityTexture.isReady()) {
  44866. return false;
  44867. }
  44868. else {
  44869. needUVs = true;
  44870. this._defines.OPACITY = true;
  44871. if (this.opacityTexture.getAlphaFromRGB) {
  44872. this._defines.OPACITYRGB = true;
  44873. }
  44874. }
  44875. }
  44876. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44877. if (!this.reflectionTexture.isReady()) {
  44878. return false;
  44879. }
  44880. else {
  44881. needNormals = true;
  44882. this._defines.REFLECTION = true;
  44883. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44884. this._defines.INVERTCUBICMAP = true;
  44885. }
  44886. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  44887. switch (this.reflectionTexture.coordinatesMode) {
  44888. case BABYLON.Texture.CUBIC_MODE:
  44889. case BABYLON.Texture.INVCUBIC_MODE:
  44890. this._defines.REFLECTIONMAP_CUBIC = true;
  44891. break;
  44892. case BABYLON.Texture.EXPLICIT_MODE:
  44893. this._defines.REFLECTIONMAP_EXPLICIT = true;
  44894. break;
  44895. case BABYLON.Texture.PLANAR_MODE:
  44896. this._defines.REFLECTIONMAP_PLANAR = true;
  44897. break;
  44898. case BABYLON.Texture.PROJECTION_MODE:
  44899. this._defines.REFLECTIONMAP_PROJECTION = true;
  44900. break;
  44901. case BABYLON.Texture.SKYBOX_MODE:
  44902. this._defines.REFLECTIONMAP_SKYBOX = true;
  44903. break;
  44904. case BABYLON.Texture.SPHERICAL_MODE:
  44905. this._defines.REFLECTIONMAP_SPHERICAL = true;
  44906. break;
  44907. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44908. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44909. break;
  44910. }
  44911. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  44912. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  44913. needNormals = true;
  44914. if (this.reflectionTexture.isPMREM) {
  44915. this._defines.USEPMREMREFLECTION = true;
  44916. }
  44917. }
  44918. }
  44919. }
  44920. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44921. if (!this.lightmapTexture.isReady()) {
  44922. return false;
  44923. }
  44924. else {
  44925. needUVs = true;
  44926. this._defines.LIGHTMAP = true;
  44927. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  44928. }
  44929. }
  44930. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44931. if (!this.emissiveTexture.isReady()) {
  44932. return false;
  44933. }
  44934. else {
  44935. needUVs = true;
  44936. this._defines.EMISSIVE = true;
  44937. }
  44938. }
  44939. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44940. if (!this.reflectivityTexture.isReady()) {
  44941. return false;
  44942. }
  44943. else {
  44944. needUVs = true;
  44945. this._defines.REFLECTIVITY = true;
  44946. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  44947. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  44948. }
  44949. }
  44950. }
  44951. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44952. if (!this.bumpTexture.isReady()) {
  44953. return false;
  44954. }
  44955. else {
  44956. needUVs = true;
  44957. this._defines.BUMP = true;
  44958. if (this.useParallax) {
  44959. this._defines.PARALLAX = true;
  44960. if (this.useParallaxOcclusion) {
  44961. this._defines.PARALLAXOCCLUSION = true;
  44962. }
  44963. }
  44964. }
  44965. }
  44966. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44967. if (!this.refractionTexture.isReady()) {
  44968. return false;
  44969. }
  44970. else {
  44971. needUVs = true;
  44972. this._defines.REFRACTION = true;
  44973. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  44974. if (this.linkRefractionWithTransparency) {
  44975. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44976. }
  44977. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  44978. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  44979. if (this.refractionTexture.isPMREM) {
  44980. this._defines.USEPMREMREFRACTION = true;
  44981. }
  44982. }
  44983. }
  44984. }
  44985. }
  44986. // Effect
  44987. if (scene.clipPlane) {
  44988. this._defines.CLIPPLANE = true;
  44989. }
  44990. if (engine.getAlphaTesting()) {
  44991. this._defines.ALPHATEST = true;
  44992. }
  44993. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44994. this._defines.ALPHAFROMALBEDO = true;
  44995. }
  44996. if (this.useEmissiveAsIllumination) {
  44997. this._defines.EMISSIVEASILLUMINATION = true;
  44998. }
  44999. if (this.linkEmissiveWithAlbedo) {
  45000. this._defines.LINKEMISSIVEWITHALBEDO = true;
  45001. }
  45002. if (this.useLogarithmicDepth) {
  45003. this._defines.LOGARITHMICDEPTH = true;
  45004. }
  45005. if (this.cameraContrast != 1) {
  45006. this._defines.CAMERACONTRAST = true;
  45007. }
  45008. if (this.cameraExposure != 1) {
  45009. this._defines.CAMERATONEMAP = true;
  45010. }
  45011. if (this.overloadedShadeIntensity != 1 ||
  45012. this.overloadedShadowIntensity != 1) {
  45013. this._defines.OVERLOADEDSHADOWVALUES = true;
  45014. }
  45015. if (this.overloadedMicroSurfaceIntensity > 0 ||
  45016. this.overloadedEmissiveIntensity > 0 ||
  45017. this.overloadedReflectivityIntensity > 0 ||
  45018. this.overloadedAlbedoIntensity > 0 ||
  45019. this.overloadedAmbientIntensity > 0 ||
  45020. this.overloadedReflectionIntensity > 0) {
  45021. this._defines.OVERLOADEDVALUES = true;
  45022. }
  45023. // Point size
  45024. if (this.pointsCloud || scene.forcePointsCloud) {
  45025. this._defines.POINTSIZE = true;
  45026. }
  45027. // Fog
  45028. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45029. this._defines.FOG = true;
  45030. }
  45031. if (scene.lightsEnabled && !this.disableLighting) {
  45032. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  45033. }
  45034. if (BABYLON.StandardMaterial.FresnelEnabled) {
  45035. // Fresnel
  45036. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  45037. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45038. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  45039. this._defines.OPACITYFRESNEL = true;
  45040. }
  45041. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45042. this._defines.EMISSIVEFRESNEL = true;
  45043. }
  45044. needNormals = true;
  45045. this._defines.FRESNEL = true;
  45046. }
  45047. }
  45048. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  45049. this._defines.SPECULAROVERALPHA = true;
  45050. }
  45051. if (this.usePhysicalLightFalloff) {
  45052. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  45053. }
  45054. if (this.useRadianceOverAlpha) {
  45055. this._defines.RADIANCEOVERALPHA = true;
  45056. }
  45057. // Attribs
  45058. if (mesh) {
  45059. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45060. this._defines.NORMAL = true;
  45061. }
  45062. if (needUVs) {
  45063. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45064. this._defines.UV1 = true;
  45065. }
  45066. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45067. this._defines.UV2 = true;
  45068. }
  45069. }
  45070. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  45071. this._defines.VERTEXCOLOR = true;
  45072. if (mesh.hasVertexAlpha) {
  45073. this._defines.VERTEXALPHA = true;
  45074. }
  45075. }
  45076. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45077. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  45078. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  45079. }
  45080. // Instances
  45081. if (useInstances) {
  45082. this._defines.INSTANCES = true;
  45083. }
  45084. }
  45085. // Get correct effect
  45086. if (!this._defines.isEqual(this._cachedDefines)) {
  45087. this._defines.cloneTo(this._cachedDefines);
  45088. scene.resetCachedMaterial();
  45089. // Fallbacks
  45090. var fallbacks = new BABYLON.EffectFallbacks();
  45091. if (this._defines.REFLECTION) {
  45092. fallbacks.addFallback(0, "REFLECTION");
  45093. }
  45094. if (this._defines.REFRACTION) {
  45095. fallbacks.addFallback(0, "REFRACTION");
  45096. }
  45097. if (this._defines.REFLECTIVITY) {
  45098. fallbacks.addFallback(0, "REFLECTIVITY");
  45099. }
  45100. if (this._defines.BUMP) {
  45101. fallbacks.addFallback(0, "BUMP");
  45102. }
  45103. if (this._defines.PARALLAX) {
  45104. fallbacks.addFallback(1, "PARALLAX");
  45105. }
  45106. if (this._defines.PARALLAXOCCLUSION) {
  45107. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  45108. }
  45109. if (this._defines.SPECULAROVERALPHA) {
  45110. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  45111. }
  45112. if (this._defines.FOG) {
  45113. fallbacks.addFallback(1, "FOG");
  45114. }
  45115. if (this._defines.POINTSIZE) {
  45116. fallbacks.addFallback(0, "POINTSIZE");
  45117. }
  45118. if (this._defines.LOGARITHMICDEPTH) {
  45119. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  45120. }
  45121. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  45122. if (this._defines.SPECULARTERM) {
  45123. fallbacks.addFallback(0, "SPECULARTERM");
  45124. }
  45125. if (this._defines.OPACITYFRESNEL) {
  45126. fallbacks.addFallback(1, "OPACITYFRESNEL");
  45127. }
  45128. if (this._defines.EMISSIVEFRESNEL) {
  45129. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  45130. }
  45131. if (this._defines.FRESNEL) {
  45132. fallbacks.addFallback(3, "FRESNEL");
  45133. }
  45134. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  45135. fallbacks.addCPUSkinningFallback(0, mesh);
  45136. }
  45137. //Attributes
  45138. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45139. if (this._defines.NORMAL) {
  45140. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45141. }
  45142. if (this._defines.UV1) {
  45143. attribs.push(BABYLON.VertexBuffer.UVKind);
  45144. }
  45145. if (this._defines.UV2) {
  45146. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45147. }
  45148. if (this._defines.VERTEXCOLOR) {
  45149. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45150. }
  45151. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  45152. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  45153. // Legacy browser patch
  45154. var shaderName = "pbr";
  45155. if (!scene.getEngine().getCaps().standardDerivatives) {
  45156. shaderName = "legacypbr";
  45157. }
  45158. var join = this._defines.toString();
  45159. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45160. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  45161. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  45162. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  45163. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  45164. "vFogInfos", "vFogColor", "pointSize",
  45165. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45166. "mBones",
  45167. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45168. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  45169. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  45170. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  45171. "logarithmicDepthConstant",
  45172. "vSphericalX", "vSphericalY", "vSphericalZ",
  45173. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45174. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45175. "vMicrosurfaceTextureLods", "vLightRadiuses"
  45176. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  45177. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  45178. ], join, fallbacks, this.onCompiled, this.onError);
  45179. }
  45180. if (!this._effect.isReady()) {
  45181. return false;
  45182. }
  45183. this._renderId = scene.getRenderId();
  45184. this._wasPreviouslyReady = true;
  45185. if (mesh) {
  45186. if (!mesh._materialDefines) {
  45187. mesh._materialDefines = new PBRMaterialDefines();
  45188. }
  45189. this._defines.cloneTo(mesh._materialDefines);
  45190. }
  45191. return true;
  45192. };
  45193. PBRMaterial.prototype.unbind = function () {
  45194. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  45195. this._effect.setTexture("reflection2DSampler", null);
  45196. }
  45197. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  45198. this._effect.setTexture("refraction2DSampler", null);
  45199. }
  45200. _super.prototype.unbind.call(this);
  45201. };
  45202. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45203. this._effect.setMatrix("world", world);
  45204. };
  45205. PBRMaterial.prototype.bind = function (world, mesh) {
  45206. this._myScene = this.getScene();
  45207. // Matrices
  45208. this.bindOnlyWorldMatrix(world);
  45209. // Bones
  45210. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45211. if (this._myScene.getCachedMaterial() !== this) {
  45212. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  45213. if (BABYLON.StandardMaterial.FresnelEnabled) {
  45214. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  45215. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  45216. }
  45217. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45218. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  45219. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  45220. }
  45221. }
  45222. // Textures
  45223. if (this._myScene.texturesEnabled) {
  45224. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45225. this._effect.setTexture("albedoSampler", this.albedoTexture);
  45226. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  45227. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  45228. }
  45229. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45230. this._effect.setTexture("ambientSampler", this.ambientTexture);
  45231. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  45232. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  45233. }
  45234. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45235. this._effect.setTexture("opacitySampler", this.opacityTexture);
  45236. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  45237. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  45238. }
  45239. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45240. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  45241. if (this.reflectionTexture.isCube) {
  45242. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  45243. }
  45244. else {
  45245. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  45246. }
  45247. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  45248. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  45249. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  45250. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  45251. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  45252. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  45253. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  45254. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  45255. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  45256. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  45257. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  45258. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  45259. }
  45260. }
  45261. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45262. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  45263. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  45264. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  45265. }
  45266. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45267. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  45268. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  45269. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  45270. }
  45271. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45272. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  45273. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  45274. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  45275. }
  45276. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  45277. this._effect.setTexture("bumpSampler", this.bumpTexture);
  45278. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  45279. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  45280. }
  45281. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45282. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  45283. var depth = 1.0;
  45284. if (this.refractionTexture.isCube) {
  45285. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  45286. }
  45287. else {
  45288. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  45289. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  45290. if (this.refractionTexture.depth) {
  45291. depth = this.refractionTexture.depth;
  45292. }
  45293. }
  45294. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  45295. }
  45296. if ((this.reflectionTexture || this.refractionTexture)) {
  45297. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  45298. }
  45299. }
  45300. // Clip plane
  45301. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  45302. // Point size
  45303. if (this.pointsCloud) {
  45304. this._effect.setFloat("pointSize", this.pointSize);
  45305. }
  45306. // Colors
  45307. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  45308. // GAMMA CORRECTION.
  45309. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  45310. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  45311. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45312. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  45313. // GAMMA CORRECTION.
  45314. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  45315. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  45316. // GAMMA CORRECTION.
  45317. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  45318. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  45319. }
  45320. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  45321. // GAMMA CORRECTION.
  45322. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  45323. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  45324. // Lights
  45325. if (this._myScene.lightsEnabled && !this.disableLighting) {
  45326. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  45327. }
  45328. // View
  45329. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  45330. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  45331. }
  45332. // Fog
  45333. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  45334. this._lightingInfos.x = this.directIntensity;
  45335. this._lightingInfos.y = this.emissiveIntensity;
  45336. this._lightingInfos.z = this.environmentIntensity;
  45337. this._lightingInfos.w = this.specularIntensity;
  45338. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  45339. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  45340. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  45341. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  45342. this._cameraInfos.x = this.cameraExposure;
  45343. this._cameraInfos.y = this.cameraContrast;
  45344. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  45345. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  45346. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  45347. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  45348. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  45349. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  45350. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  45351. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  45352. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  45353. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  45354. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  45355. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  45356. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  45357. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  45358. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  45359. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  45360. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  45361. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  45362. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  45363. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  45364. // Log. depth
  45365. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  45366. }
  45367. _super.prototype.bind.call(this, world, mesh);
  45368. this._myScene = null;
  45369. };
  45370. PBRMaterial.prototype.getAnimatables = function () {
  45371. var results = [];
  45372. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  45373. results.push(this.albedoTexture);
  45374. }
  45375. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  45376. results.push(this.ambientTexture);
  45377. }
  45378. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  45379. results.push(this.opacityTexture);
  45380. }
  45381. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  45382. results.push(this.reflectionTexture);
  45383. }
  45384. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  45385. results.push(this.emissiveTexture);
  45386. }
  45387. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  45388. results.push(this.reflectivityTexture);
  45389. }
  45390. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  45391. results.push(this.bumpTexture);
  45392. }
  45393. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  45394. results.push(this.lightmapTexture);
  45395. }
  45396. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  45397. results.push(this.refractionTexture);
  45398. }
  45399. return results;
  45400. };
  45401. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45402. if (forceDisposeTextures) {
  45403. if (this.albedoTexture) {
  45404. this.albedoTexture.dispose();
  45405. }
  45406. if (this.ambientTexture) {
  45407. this.ambientTexture.dispose();
  45408. }
  45409. if (this.opacityTexture) {
  45410. this.opacityTexture.dispose();
  45411. }
  45412. if (this.reflectionTexture) {
  45413. this.reflectionTexture.dispose();
  45414. }
  45415. if (this.emissiveTexture) {
  45416. this.emissiveTexture.dispose();
  45417. }
  45418. if (this.reflectivityTexture) {
  45419. this.reflectivityTexture.dispose();
  45420. }
  45421. if (this.bumpTexture) {
  45422. this.bumpTexture.dispose();
  45423. }
  45424. if (this.lightmapTexture) {
  45425. this.lightmapTexture.dispose();
  45426. }
  45427. if (this.refractionTexture) {
  45428. this.refractionTexture.dispose();
  45429. }
  45430. }
  45431. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45432. };
  45433. PBRMaterial.prototype.clone = function (name) {
  45434. var _this = this;
  45435. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45436. };
  45437. PBRMaterial.prototype.serialize = function () {
  45438. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45439. serializationObject.customType = "BABYLON.PBRMaterial";
  45440. return serializationObject;
  45441. };
  45442. // Statics
  45443. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45444. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45445. };
  45446. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  45447. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  45448. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  45449. PBRMaterial._scaledReflection = new BABYLON.Color3();
  45450. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  45451. __decorate([
  45452. BABYLON.serialize()
  45453. ], PBRMaterial.prototype, "directIntensity", void 0);
  45454. __decorate([
  45455. BABYLON.serialize()
  45456. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45457. __decorate([
  45458. BABYLON.serialize()
  45459. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45460. __decorate([
  45461. BABYLON.serialize()
  45462. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45463. __decorate([
  45464. BABYLON.serialize()
  45465. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45466. __decorate([
  45467. BABYLON.serialize()
  45468. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  45469. __decorate([
  45470. BABYLON.serialize()
  45471. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  45472. __decorate([
  45473. BABYLON.serialize()
  45474. ], PBRMaterial.prototype, "cameraExposure", void 0);
  45475. __decorate([
  45476. BABYLON.serialize()
  45477. ], PBRMaterial.prototype, "cameraContrast", void 0);
  45478. __decorate([
  45479. BABYLON.serializeAsColor3()
  45480. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  45481. __decorate([
  45482. BABYLON.serialize()
  45483. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  45484. __decorate([
  45485. BABYLON.serializeAsColor3()
  45486. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  45487. __decorate([
  45488. BABYLON.serialize()
  45489. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  45490. __decorate([
  45491. BABYLON.serializeAsColor3()
  45492. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  45493. __decorate([
  45494. BABYLON.serialize()
  45495. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  45496. __decorate([
  45497. BABYLON.serializeAsColor3()
  45498. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  45499. __decorate([
  45500. BABYLON.serialize()
  45501. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  45502. __decorate([
  45503. BABYLON.serializeAsColor3()
  45504. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  45505. __decorate([
  45506. BABYLON.serialize()
  45507. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  45508. __decorate([
  45509. BABYLON.serialize()
  45510. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  45511. __decorate([
  45512. BABYLON.serialize()
  45513. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  45514. __decorate([
  45515. BABYLON.serializeAsTexture()
  45516. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45517. __decorate([
  45518. BABYLON.serializeAsTexture()
  45519. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45520. __decorate([
  45521. BABYLON.serializeAsTexture()
  45522. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45523. __decorate([
  45524. BABYLON.serializeAsTexture()
  45525. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45526. __decorate([
  45527. BABYLON.serializeAsTexture()
  45528. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45529. __decorate([
  45530. BABYLON.serializeAsTexture()
  45531. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45532. __decorate([
  45533. BABYLON.serializeAsTexture()
  45534. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45535. __decorate([
  45536. BABYLON.serializeAsTexture()
  45537. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45538. __decorate([
  45539. BABYLON.serializeAsTexture()
  45540. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45541. __decorate([
  45542. BABYLON.serializeAsColor3("ambient")
  45543. ], PBRMaterial.prototype, "ambientColor", void 0);
  45544. __decorate([
  45545. BABYLON.serializeAsColor3("albedo")
  45546. ], PBRMaterial.prototype, "albedoColor", void 0);
  45547. __decorate([
  45548. BABYLON.serializeAsColor3("reflectivity")
  45549. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45550. __decorate([
  45551. BABYLON.serializeAsColor3("reflection")
  45552. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45553. __decorate([
  45554. BABYLON.serializeAsColor3("emissive")
  45555. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45556. __decorate([
  45557. BABYLON.serialize()
  45558. ], PBRMaterial.prototype, "microSurface", void 0);
  45559. __decorate([
  45560. BABYLON.serialize()
  45561. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45562. __decorate([
  45563. BABYLON.serialize()
  45564. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45565. __decorate([
  45566. BABYLON.serializeAsFresnelParameters()
  45567. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  45568. __decorate([
  45569. BABYLON.serializeAsFresnelParameters()
  45570. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  45571. __decorate([
  45572. BABYLON.serialize()
  45573. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45574. __decorate([
  45575. BABYLON.serialize()
  45576. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  45577. __decorate([
  45578. BABYLON.serialize()
  45579. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45580. __decorate([
  45581. BABYLON.serialize()
  45582. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45583. __decorate([
  45584. BABYLON.serialize()
  45585. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45586. __decorate([
  45587. BABYLON.serialize()
  45588. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45589. __decorate([
  45590. BABYLON.serialize()
  45591. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45592. __decorate([
  45593. BABYLON.serialize()
  45594. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45595. __decorate([
  45596. BABYLON.serialize()
  45597. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  45598. __decorate([
  45599. BABYLON.serialize()
  45600. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45601. __decorate([
  45602. BABYLON.serialize()
  45603. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45604. __decorate([
  45605. BABYLON.serialize()
  45606. ], PBRMaterial.prototype, "useParallax", void 0);
  45607. __decorate([
  45608. BABYLON.serialize()
  45609. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45610. __decorate([
  45611. BABYLON.serialize()
  45612. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45613. __decorate([
  45614. BABYLON.serialize()
  45615. ], PBRMaterial.prototype, "disableLighting", void 0);
  45616. __decorate([
  45617. BABYLON.serialize()
  45618. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  45619. return PBRMaterial;
  45620. })(BABYLON.Material);
  45621. BABYLON.PBRMaterial = PBRMaterial;
  45622. })(BABYLON || (BABYLON = {}));
  45623. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightRadiuses;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0 ,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0 ,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  45624. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,glossiness);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nshadow=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,-lightDirection.xyz));\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW-lightDirection.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,vec3(1.,1.,1.));\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\nfloat computeLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\nreturn lightDistanceFalloff;\n#else\nfloat lightFalloff=max(0.,1.0-length(lightOffset)/range);\nreturn lightFalloff;\n#endif\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(lightOffset);\n\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection.xyz,lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeLightFalloff(lightOffset,lightDistanceSquared,range);\n\nattenuation*=cosAngle;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,float lightRadius,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,vLightRadiuses[{X}],NdotL);\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#if defined(POINTLIGHT0) || defined(POINTLIGHT1) || defined(POINTLIGHT2) || defined(POINTLIGHT3)\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n#endif\n#if defined(SPOTLIGHT0) || defined(SPOTLIGHT1) || defined(SPOTLIGHT2) || defined(SPOTLIGHT3) || defined(DIRLIGHT0) || defined(DIRLIGHT1) || defined(DIRLIGHT2) || defined(DIRLIGHT3)\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\nreturn min(1.0,visibility+darkness);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nvPositionFromLight0=lightMatrix0*worldPos;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nvPositionFromLight1=lightMatrix1*worldPos;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nvPositionFromLight2=lightMatrix2*worldPos;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nvPositionFromLight3=lightMatrix3*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT0) || defined(DIRLIGHT0)\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#if defined(SPOTLIGHT1) || defined(DIRLIGHT1)\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#if defined(SPOTLIGHT2) || defined(DIRLIGHT2)\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#if defined(SPOTLIGHT3) || defined(DIRLIGHT3)\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif"};
  45625. 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=2*g*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=2*g*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=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new h(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new s(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,s=t.w-i.w;return n*n+r*r+o*o+s*s},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=e;var h=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new s(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;16>n;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],s=this.m[2],e=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*F+s*P+e*I,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*F+z*P+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(0>t||t>3)return null;var i=4*t;return new e(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(0>t||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){var z=new t;return z.m[0]=i,z.m[1]=n,z.m[2]=r,z.m[3]=o,z.m[4]=s,z.m[5]=e,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=l,z.m[15]=x,z},t.Compose=function(i,n,r){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;\n\nreturn t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),s=1-o;t.normalize(),n.m[0]=t.x*t.x*s+o,n.m[1]=t.x*t.y*s-t.z*r,n.m[2]=t.x*t.z*s+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*s+t.z*r,n.m[5]=t.y*t.y*s+o,n.m[6]=t.y*t.z*s-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*s-t.y*r,n.m[9]=t.z*t.y*s+t.x*r,n.m[10]=t.z*t.z*s+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);o.m[0]=s?e/i:e,o.m[1]=o.m[2]=o.m[3]=0,o.m[5]=s?e:e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=a.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=u;var m=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  45626. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  45627. module.exports = BABYLON;
  45628. };