babylon.max.js 2.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117
  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]) + transformation.m[12];
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  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 Size = (function () {
  1273. function Size(width, height) {
  1274. this.width = width;
  1275. this.height = height;
  1276. }
  1277. Size.prototype.clone = function () {
  1278. return new Size(this.width, this.height);
  1279. };
  1280. Size.prototype.equals = function (other) {
  1281. if (!other) {
  1282. return false;
  1283. }
  1284. return (this.width === other.width) && (this.height === other.height);
  1285. };
  1286. Object.defineProperty(Size.prototype, "surface", {
  1287. get: function () {
  1288. return this.width * this.height;
  1289. },
  1290. enumerable: true,
  1291. configurable: true
  1292. });
  1293. Size.Zero = function () {
  1294. return new Size(0, 0);
  1295. };
  1296. return Size;
  1297. })();
  1298. BABYLON.Size = Size;
  1299. var Quaternion = (function () {
  1300. function Quaternion(x, y, z, w) {
  1301. if (x === void 0) { x = 0; }
  1302. if (y === void 0) { y = 0; }
  1303. if (z === void 0) { z = 0; }
  1304. if (w === void 0) { w = 1; }
  1305. this.x = x;
  1306. this.y = y;
  1307. this.z = z;
  1308. this.w = w;
  1309. }
  1310. Quaternion.prototype.toString = function () {
  1311. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1312. };
  1313. Quaternion.prototype.asArray = function () {
  1314. return [this.x, this.y, this.z, this.w];
  1315. };
  1316. Quaternion.prototype.equals = function (otherQuaternion) {
  1317. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1318. };
  1319. Quaternion.prototype.clone = function () {
  1320. return new Quaternion(this.x, this.y, this.z, this.w);
  1321. };
  1322. Quaternion.prototype.copyFrom = function (other) {
  1323. this.x = other.x;
  1324. this.y = other.y;
  1325. this.z = other.z;
  1326. this.w = other.w;
  1327. return this;
  1328. };
  1329. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1330. this.x = x;
  1331. this.y = y;
  1332. this.z = z;
  1333. this.w = w;
  1334. return this;
  1335. };
  1336. Quaternion.prototype.add = function (other) {
  1337. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1338. };
  1339. Quaternion.prototype.subtract = function (other) {
  1340. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1341. };
  1342. Quaternion.prototype.scale = function (value) {
  1343. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1344. };
  1345. Quaternion.prototype.multiply = function (q1) {
  1346. var result = new Quaternion(0, 0, 0, 1.0);
  1347. this.multiplyToRef(q1, result);
  1348. return result;
  1349. };
  1350. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1351. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1352. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1353. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1354. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1355. result.copyFromFloats(x, y, z, w);
  1356. return this;
  1357. };
  1358. Quaternion.prototype.multiplyInPlace = function (q1) {
  1359. this.multiplyToRef(q1, this);
  1360. return this;
  1361. };
  1362. Quaternion.prototype.conjugateToRef = function (ref) {
  1363. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1364. return this;
  1365. };
  1366. Quaternion.prototype.conjugateInPlace = function () {
  1367. this.x *= -1;
  1368. this.y *= -1;
  1369. this.z *= -1;
  1370. return this;
  1371. };
  1372. Quaternion.prototype.conjugate = function () {
  1373. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1374. return result;
  1375. };
  1376. Quaternion.prototype.length = function () {
  1377. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1378. };
  1379. Quaternion.prototype.normalize = function () {
  1380. var length = 1.0 / this.length();
  1381. this.x *= length;
  1382. this.y *= length;
  1383. this.z *= length;
  1384. this.w *= length;
  1385. return this;
  1386. };
  1387. Quaternion.prototype.toEulerAngles = function (order) {
  1388. if (order === void 0) { order = "YZX"; }
  1389. var result = Vector3.Zero();
  1390. this.toEulerAnglesToRef(result, order);
  1391. return result;
  1392. };
  1393. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1394. if (order === void 0) { order = "YZX"; }
  1395. var heading, attitude, bank;
  1396. var x = this.x, y = this.y, z = this.z, w = this.w;
  1397. switch (order) {
  1398. case "YZX":
  1399. var test = x * y + z * w;
  1400. if (test > 0.499) {
  1401. heading = 2 * Math.atan2(x, w);
  1402. attitude = Math.PI / 2;
  1403. bank = 0;
  1404. }
  1405. if (test < -0.499) {
  1406. heading = -2 * Math.atan2(x, w);
  1407. attitude = -Math.PI / 2;
  1408. bank = 0;
  1409. }
  1410. if (isNaN(heading)) {
  1411. var sqx = x * x;
  1412. var sqy = y * y;
  1413. var sqz = z * z;
  1414. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1415. attitude = Math.asin(2 * test); // attitude
  1416. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1417. }
  1418. break;
  1419. default:
  1420. throw new Error("Euler order " + order + " not supported yet.");
  1421. }
  1422. result.y = heading;
  1423. result.z = attitude;
  1424. result.x = bank;
  1425. return this;
  1426. };
  1427. ;
  1428. Quaternion.prototype.toRotationMatrix = function (result) {
  1429. var xx = this.x * this.x;
  1430. var yy = this.y * this.y;
  1431. var zz = this.z * this.z;
  1432. var xy = this.x * this.y;
  1433. var zw = this.z * this.w;
  1434. var zx = this.z * this.x;
  1435. var yw = this.y * this.w;
  1436. var yz = this.y * this.z;
  1437. var xw = this.x * this.w;
  1438. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1439. result.m[1] = 2.0 * (xy + zw);
  1440. result.m[2] = 2.0 * (zx - yw);
  1441. result.m[3] = 0;
  1442. result.m[4] = 2.0 * (xy - zw);
  1443. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1444. result.m[6] = 2.0 * (yz + xw);
  1445. result.m[7] = 0;
  1446. result.m[8] = 2.0 * (zx + yw);
  1447. result.m[9] = 2.0 * (yz - xw);
  1448. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1449. result.m[11] = 0;
  1450. result.m[12] = 0;
  1451. result.m[13] = 0;
  1452. result.m[14] = 0;
  1453. result.m[15] = 1.0;
  1454. return this;
  1455. };
  1456. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1457. Quaternion.FromRotationMatrixToRef(matrix, this);
  1458. return this;
  1459. };
  1460. // Statics
  1461. Quaternion.FromRotationMatrix = function (matrix) {
  1462. var result = new Quaternion();
  1463. Quaternion.FromRotationMatrixToRef(matrix, result);
  1464. return result;
  1465. };
  1466. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1467. var data = matrix.m;
  1468. var m11 = data[0], m12 = data[4], m13 = data[8];
  1469. var m21 = data[1], m22 = data[5], m23 = data[9];
  1470. var m31 = data[2], m32 = data[6], m33 = data[10];
  1471. var trace = m11 + m22 + m33;
  1472. var s;
  1473. if (trace > 0) {
  1474. s = 0.5 / Math.sqrt(trace + 1.0);
  1475. result.w = 0.25 / s;
  1476. result.x = (m32 - m23) * s;
  1477. result.y = (m13 - m31) * s;
  1478. result.z = (m21 - m12) * s;
  1479. }
  1480. else if (m11 > m22 && m11 > m33) {
  1481. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1482. result.w = (m32 - m23) / s;
  1483. result.x = 0.25 * s;
  1484. result.y = (m12 + m21) / s;
  1485. result.z = (m13 + m31) / s;
  1486. }
  1487. else if (m22 > m33) {
  1488. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1489. result.w = (m13 - m31) / s;
  1490. result.x = (m12 + m21) / s;
  1491. result.y = 0.25 * s;
  1492. result.z = (m23 + m32) / s;
  1493. }
  1494. else {
  1495. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1496. result.w = (m21 - m12) / s;
  1497. result.x = (m13 + m31) / s;
  1498. result.y = (m23 + m32) / s;
  1499. result.z = 0.25 * s;
  1500. }
  1501. };
  1502. Quaternion.Inverse = function (q) {
  1503. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1504. };
  1505. Quaternion.Identity = function () {
  1506. return new Quaternion(0, 0, 0, 1);
  1507. };
  1508. Quaternion.RotationAxis = function (axis, angle) {
  1509. var result = new Quaternion();
  1510. var sin = Math.sin(angle / 2);
  1511. axis.normalize();
  1512. result.w = Math.cos(angle / 2);
  1513. result.x = axis.x * sin;
  1514. result.y = axis.y * sin;
  1515. result.z = axis.z * sin;
  1516. return result;
  1517. };
  1518. Quaternion.FromArray = function (array, offset) {
  1519. if (!offset) {
  1520. offset = 0;
  1521. }
  1522. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1523. };
  1524. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1525. var result = new Quaternion();
  1526. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1527. return result;
  1528. };
  1529. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1530. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1531. var halfRoll = roll * 0.5;
  1532. var halfPitch = pitch * 0.5;
  1533. var halfYaw = yaw * 0.5;
  1534. var sinRoll = Math.sin(halfRoll);
  1535. var cosRoll = Math.cos(halfRoll);
  1536. var sinPitch = Math.sin(halfPitch);
  1537. var cosPitch = Math.cos(halfPitch);
  1538. var sinYaw = Math.sin(halfYaw);
  1539. var cosYaw = Math.cos(halfYaw);
  1540. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1541. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1542. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1543. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1544. };
  1545. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1546. var result = new Quaternion();
  1547. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1548. return result;
  1549. };
  1550. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1551. // Produces a quaternion from Euler angles in the z-x-z orientation
  1552. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1553. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1554. var halfBeta = beta * 0.5;
  1555. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1556. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1557. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1558. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1559. };
  1560. Quaternion.Slerp = function (left, right, amount) {
  1561. var num2;
  1562. var num3;
  1563. var num = amount;
  1564. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1565. var flag = false;
  1566. if (num4 < 0) {
  1567. flag = true;
  1568. num4 = -num4;
  1569. }
  1570. if (num4 > 0.999999) {
  1571. num3 = 1 - num;
  1572. num2 = flag ? -num : num;
  1573. }
  1574. else {
  1575. var num5 = Math.acos(num4);
  1576. var num6 = (1.0 / Math.sin(num5));
  1577. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1578. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1579. }
  1580. 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));
  1581. };
  1582. return Quaternion;
  1583. })();
  1584. BABYLON.Quaternion = Quaternion;
  1585. var Matrix = (function () {
  1586. function Matrix() {
  1587. this.m = new Float32Array(16);
  1588. }
  1589. // Properties
  1590. Matrix.prototype.isIdentity = function () {
  1591. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1592. return false;
  1593. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1594. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1595. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1596. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1597. return false;
  1598. return true;
  1599. };
  1600. Matrix.prototype.determinant = function () {
  1601. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1602. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1603. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1604. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1605. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1606. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1607. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1608. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1609. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1610. };
  1611. // Methods
  1612. Matrix.prototype.toArray = function () {
  1613. return this.m;
  1614. };
  1615. Matrix.prototype.asArray = function () {
  1616. return this.toArray();
  1617. };
  1618. Matrix.prototype.invert = function () {
  1619. this.invertToRef(this);
  1620. return this;
  1621. };
  1622. Matrix.prototype.reset = function () {
  1623. for (var index = 0; index < 16; index++) {
  1624. this.m[index] = 0;
  1625. }
  1626. return this;
  1627. };
  1628. Matrix.prototype.add = function (other) {
  1629. var result = new Matrix();
  1630. this.addToRef(other, result);
  1631. return result;
  1632. };
  1633. Matrix.prototype.addToRef = function (other, result) {
  1634. for (var index = 0; index < 16; index++) {
  1635. result.m[index] = this.m[index] + other.m[index];
  1636. }
  1637. return this;
  1638. };
  1639. Matrix.prototype.addToSelf = function (other) {
  1640. for (var index = 0; index < 16; index++) {
  1641. this.m[index] += other.m[index];
  1642. }
  1643. return this;
  1644. };
  1645. Matrix.prototype.invertToRef = function (other) {
  1646. var l1 = this.m[0];
  1647. var l2 = this.m[1];
  1648. var l3 = this.m[2];
  1649. var l4 = this.m[3];
  1650. var l5 = this.m[4];
  1651. var l6 = this.m[5];
  1652. var l7 = this.m[6];
  1653. var l8 = this.m[7];
  1654. var l9 = this.m[8];
  1655. var l10 = this.m[9];
  1656. var l11 = this.m[10];
  1657. var l12 = this.m[11];
  1658. var l13 = this.m[12];
  1659. var l14 = this.m[13];
  1660. var l15 = this.m[14];
  1661. var l16 = this.m[15];
  1662. var l17 = (l11 * l16) - (l12 * l15);
  1663. var l18 = (l10 * l16) - (l12 * l14);
  1664. var l19 = (l10 * l15) - (l11 * l14);
  1665. var l20 = (l9 * l16) - (l12 * l13);
  1666. var l21 = (l9 * l15) - (l11 * l13);
  1667. var l22 = (l9 * l14) - (l10 * l13);
  1668. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1669. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1670. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1671. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1672. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1673. var l28 = (l7 * l16) - (l8 * l15);
  1674. var l29 = (l6 * l16) - (l8 * l14);
  1675. var l30 = (l6 * l15) - (l7 * l14);
  1676. var l31 = (l5 * l16) - (l8 * l13);
  1677. var l32 = (l5 * l15) - (l7 * l13);
  1678. var l33 = (l5 * l14) - (l6 * l13);
  1679. var l34 = (l7 * l12) - (l8 * l11);
  1680. var l35 = (l6 * l12) - (l8 * l10);
  1681. var l36 = (l6 * l11) - (l7 * l10);
  1682. var l37 = (l5 * l12) - (l8 * l9);
  1683. var l38 = (l5 * l11) - (l7 * l9);
  1684. var l39 = (l5 * l10) - (l6 * l9);
  1685. other.m[0] = l23 * l27;
  1686. other.m[4] = l24 * l27;
  1687. other.m[8] = l25 * l27;
  1688. other.m[12] = l26 * l27;
  1689. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1690. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1691. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1692. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1693. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1694. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1695. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1696. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1697. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1698. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1699. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1700. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1701. return this;
  1702. };
  1703. Matrix.prototype.setTranslation = function (vector3) {
  1704. this.m[12] = vector3.x;
  1705. this.m[13] = vector3.y;
  1706. this.m[14] = vector3.z;
  1707. return this;
  1708. };
  1709. Matrix.prototype.getTranslation = function () {
  1710. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1711. };
  1712. Matrix.prototype.multiply = function (other) {
  1713. var result = new Matrix();
  1714. this.multiplyToRef(other, result);
  1715. return result;
  1716. };
  1717. Matrix.prototype.copyFrom = function (other) {
  1718. for (var index = 0; index < 16; index++) {
  1719. this.m[index] = other.m[index];
  1720. }
  1721. return this;
  1722. };
  1723. Matrix.prototype.copyToArray = function (array, offset) {
  1724. if (offset === void 0) { offset = 0; }
  1725. for (var index = 0; index < 16; index++) {
  1726. array[offset + index] = this.m[index];
  1727. }
  1728. return this;
  1729. };
  1730. Matrix.prototype.multiplyToRef = function (other, result) {
  1731. this.multiplyToArray(other, result.m, 0);
  1732. return this;
  1733. };
  1734. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1735. var tm0 = this.m[0];
  1736. var tm1 = this.m[1];
  1737. var tm2 = this.m[2];
  1738. var tm3 = this.m[3];
  1739. var tm4 = this.m[4];
  1740. var tm5 = this.m[5];
  1741. var tm6 = this.m[6];
  1742. var tm7 = this.m[7];
  1743. var tm8 = this.m[8];
  1744. var tm9 = this.m[9];
  1745. var tm10 = this.m[10];
  1746. var tm11 = this.m[11];
  1747. var tm12 = this.m[12];
  1748. var tm13 = this.m[13];
  1749. var tm14 = this.m[14];
  1750. var tm15 = this.m[15];
  1751. var om0 = other.m[0];
  1752. var om1 = other.m[1];
  1753. var om2 = other.m[2];
  1754. var om3 = other.m[3];
  1755. var om4 = other.m[4];
  1756. var om5 = other.m[5];
  1757. var om6 = other.m[6];
  1758. var om7 = other.m[7];
  1759. var om8 = other.m[8];
  1760. var om9 = other.m[9];
  1761. var om10 = other.m[10];
  1762. var om11 = other.m[11];
  1763. var om12 = other.m[12];
  1764. var om13 = other.m[13];
  1765. var om14 = other.m[14];
  1766. var om15 = other.m[15];
  1767. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1768. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1769. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1770. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1771. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1772. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1773. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1774. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1775. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1776. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1777. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1778. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1779. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1780. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1781. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1782. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1783. return this;
  1784. };
  1785. Matrix.prototype.equals = function (value) {
  1786. return value &&
  1787. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1788. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1789. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1790. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1791. };
  1792. Matrix.prototype.clone = function () {
  1793. 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]);
  1794. };
  1795. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1796. translation.x = this.m[12];
  1797. translation.y = this.m[13];
  1798. translation.z = this.m[14];
  1799. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1800. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1801. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1802. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1803. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1804. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1805. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1806. rotation.x = 0;
  1807. rotation.y = 0;
  1808. rotation.z = 0;
  1809. rotation.w = 1;
  1810. return false;
  1811. }
  1812. 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);
  1813. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1814. return true;
  1815. };
  1816. // Statics
  1817. Matrix.FromArray = function (array, offset) {
  1818. var result = new Matrix();
  1819. if (!offset) {
  1820. offset = 0;
  1821. }
  1822. Matrix.FromArrayToRef(array, offset, result);
  1823. return result;
  1824. };
  1825. Matrix.FromArrayToRef = function (array, offset, result) {
  1826. for (var index = 0; index < 16; index++) {
  1827. result.m[index] = array[index + offset];
  1828. }
  1829. };
  1830. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1831. for (var index = 0; index < 16; index++) {
  1832. result.m[index] = array[index + offset] * scale;
  1833. }
  1834. };
  1835. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1836. result.m[0] = initialM11;
  1837. result.m[1] = initialM12;
  1838. result.m[2] = initialM13;
  1839. result.m[3] = initialM14;
  1840. result.m[4] = initialM21;
  1841. result.m[5] = initialM22;
  1842. result.m[6] = initialM23;
  1843. result.m[7] = initialM24;
  1844. result.m[8] = initialM31;
  1845. result.m[9] = initialM32;
  1846. result.m[10] = initialM33;
  1847. result.m[11] = initialM34;
  1848. result.m[12] = initialM41;
  1849. result.m[13] = initialM42;
  1850. result.m[14] = initialM43;
  1851. result.m[15] = initialM44;
  1852. };
  1853. Matrix.prototype.getRow = function (index) {
  1854. if (index < 0 || index > 3) {
  1855. return null;
  1856. }
  1857. var i = index * 4;
  1858. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  1859. };
  1860. Matrix.prototype.setRow = function (index, row) {
  1861. if (index < 0 || index > 3) {
  1862. return this;
  1863. }
  1864. var i = index * 4;
  1865. this.m[i + 0] = row.x;
  1866. this.m[i + 1] = row.y;
  1867. this.m[i + 2] = row.z;
  1868. this.m[i + 3] = row.w;
  1869. return this;
  1870. };
  1871. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1872. var result = new Matrix();
  1873. result.m[0] = initialM11;
  1874. result.m[1] = initialM12;
  1875. result.m[2] = initialM13;
  1876. result.m[3] = initialM14;
  1877. result.m[4] = initialM21;
  1878. result.m[5] = initialM22;
  1879. result.m[6] = initialM23;
  1880. result.m[7] = initialM24;
  1881. result.m[8] = initialM31;
  1882. result.m[9] = initialM32;
  1883. result.m[10] = initialM33;
  1884. result.m[11] = initialM34;
  1885. result.m[12] = initialM41;
  1886. result.m[13] = initialM42;
  1887. result.m[14] = initialM43;
  1888. result.m[15] = initialM44;
  1889. return result;
  1890. };
  1891. Matrix.Compose = function (scale, rotation, translation) {
  1892. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1893. var rotationMatrix = Matrix.Identity();
  1894. rotation.toRotationMatrix(rotationMatrix);
  1895. result = result.multiply(rotationMatrix);
  1896. result.setTranslation(translation);
  1897. return result;
  1898. };
  1899. Matrix.Identity = function () {
  1900. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1901. };
  1902. Matrix.IdentityToRef = function (result) {
  1903. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1904. };
  1905. Matrix.Zero = function () {
  1906. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1907. };
  1908. Matrix.RotationX = function (angle) {
  1909. var result = new Matrix();
  1910. Matrix.RotationXToRef(angle, result);
  1911. return result;
  1912. };
  1913. Matrix.Invert = function (source) {
  1914. var result = new Matrix();
  1915. source.invertToRef(result);
  1916. return result;
  1917. };
  1918. Matrix.RotationXToRef = function (angle, result) {
  1919. var s = Math.sin(angle);
  1920. var c = Math.cos(angle);
  1921. result.m[0] = 1.0;
  1922. result.m[15] = 1.0;
  1923. result.m[5] = c;
  1924. result.m[10] = c;
  1925. result.m[9] = -s;
  1926. result.m[6] = s;
  1927. result.m[1] = 0;
  1928. result.m[2] = 0;
  1929. result.m[3] = 0;
  1930. result.m[4] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[11] = 0;
  1934. result.m[12] = 0;
  1935. result.m[13] = 0;
  1936. result.m[14] = 0;
  1937. };
  1938. Matrix.RotationY = function (angle) {
  1939. var result = new Matrix();
  1940. Matrix.RotationYToRef(angle, result);
  1941. return result;
  1942. };
  1943. Matrix.RotationYToRef = function (angle, result) {
  1944. var s = Math.sin(angle);
  1945. var c = Math.cos(angle);
  1946. result.m[5] = 1.0;
  1947. result.m[15] = 1.0;
  1948. result.m[0] = c;
  1949. result.m[2] = -s;
  1950. result.m[8] = s;
  1951. result.m[10] = c;
  1952. result.m[1] = 0;
  1953. result.m[3] = 0;
  1954. result.m[4] = 0;
  1955. result.m[6] = 0;
  1956. result.m[7] = 0;
  1957. result.m[9] = 0;
  1958. result.m[11] = 0;
  1959. result.m[12] = 0;
  1960. result.m[13] = 0;
  1961. result.m[14] = 0;
  1962. };
  1963. Matrix.RotationZ = function (angle) {
  1964. var result = new Matrix();
  1965. Matrix.RotationZToRef(angle, result);
  1966. return result;
  1967. };
  1968. Matrix.RotationZToRef = function (angle, result) {
  1969. var s = Math.sin(angle);
  1970. var c = Math.cos(angle);
  1971. result.m[10] = 1.0;
  1972. result.m[15] = 1.0;
  1973. result.m[0] = c;
  1974. result.m[1] = s;
  1975. result.m[4] = -s;
  1976. result.m[5] = c;
  1977. result.m[2] = 0;
  1978. result.m[3] = 0;
  1979. result.m[6] = 0;
  1980. result.m[7] = 0;
  1981. result.m[8] = 0;
  1982. result.m[9] = 0;
  1983. result.m[11] = 0;
  1984. result.m[12] = 0;
  1985. result.m[13] = 0;
  1986. result.m[14] = 0;
  1987. };
  1988. Matrix.RotationAxis = function (axis, angle) {
  1989. var result = Matrix.Zero();
  1990. Matrix.RotationAxisToRef(axis, angle, result);
  1991. return result;
  1992. };
  1993. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1994. var s = Math.sin(-angle);
  1995. var c = Math.cos(-angle);
  1996. var c1 = 1 - c;
  1997. axis.normalize();
  1998. result.m[0] = (axis.x * axis.x) * c1 + c;
  1999. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2000. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2001. result.m[3] = 0.0;
  2002. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2003. result.m[5] = (axis.y * axis.y) * c1 + c;
  2004. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2005. result.m[7] = 0.0;
  2006. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2007. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2008. result.m[10] = (axis.z * axis.z) * c1 + c;
  2009. result.m[11] = 0.0;
  2010. result.m[15] = 1.0;
  2011. };
  2012. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2013. var result = new Matrix();
  2014. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2015. return result;
  2016. };
  2017. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2018. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2019. this._tempQuaternion.toRotationMatrix(result);
  2020. };
  2021. Matrix.Scaling = function (x, y, z) {
  2022. var result = Matrix.Zero();
  2023. Matrix.ScalingToRef(x, y, z, result);
  2024. return result;
  2025. };
  2026. Matrix.ScalingToRef = function (x, y, z, result) {
  2027. result.m[0] = x;
  2028. result.m[1] = 0;
  2029. result.m[2] = 0;
  2030. result.m[3] = 0;
  2031. result.m[4] = 0;
  2032. result.m[5] = y;
  2033. result.m[6] = 0;
  2034. result.m[7] = 0;
  2035. result.m[8] = 0;
  2036. result.m[9] = 0;
  2037. result.m[10] = z;
  2038. result.m[11] = 0;
  2039. result.m[12] = 0;
  2040. result.m[13] = 0;
  2041. result.m[14] = 0;
  2042. result.m[15] = 1.0;
  2043. };
  2044. Matrix.Translation = function (x, y, z) {
  2045. var result = Matrix.Identity();
  2046. Matrix.TranslationToRef(x, y, z, result);
  2047. return result;
  2048. };
  2049. Matrix.TranslationToRef = function (x, y, z, result) {
  2050. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2051. };
  2052. Matrix.Lerp = function (startValue, endValue, gradient) {
  2053. var startScale = new Vector3(0, 0, 0);
  2054. var startRotation = new Quaternion();
  2055. var startTranslation = new Vector3(0, 0, 0);
  2056. startValue.decompose(startScale, startRotation, startTranslation);
  2057. var endScale = new Vector3(0, 0, 0);
  2058. var endRotation = new Quaternion();
  2059. var endTranslation = new Vector3(0, 0, 0);
  2060. endValue.decompose(endScale, endRotation, endTranslation);
  2061. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2062. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2063. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2064. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2065. };
  2066. Matrix.LookAtLH = function (eye, target, up) {
  2067. var result = Matrix.Zero();
  2068. Matrix.LookAtLHToRef(eye, target, up, result);
  2069. return result;
  2070. };
  2071. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2072. // Z axis
  2073. target.subtractToRef(eye, this._zAxis);
  2074. this._zAxis.normalize();
  2075. // X axis
  2076. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2077. if (this._xAxis.lengthSquared() === 0) {
  2078. this._xAxis.x = 1.0;
  2079. }
  2080. else {
  2081. this._xAxis.normalize();
  2082. }
  2083. // Y axis
  2084. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2085. this._yAxis.normalize();
  2086. // Eye angles
  2087. var ex = -Vector3.Dot(this._xAxis, eye);
  2088. var ey = -Vector3.Dot(this._yAxis, eye);
  2089. var ez = -Vector3.Dot(this._zAxis, eye);
  2090. 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);
  2091. };
  2092. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2093. var matrix = Matrix.Zero();
  2094. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2095. return matrix;
  2096. };
  2097. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2098. var hw = 2.0 / width;
  2099. var hh = 2.0 / height;
  2100. var id = 1.0 / (zfar - znear);
  2101. var nid = znear / (znear - zfar);
  2102. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2103. };
  2104. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2105. var matrix = Matrix.Zero();
  2106. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2107. return matrix;
  2108. };
  2109. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2110. result.m[0] = 2.0 / (right - left);
  2111. result.m[1] = result.m[2] = result.m[3] = 0;
  2112. result.m[5] = 2.0 / (top - bottom);
  2113. result.m[4] = result.m[6] = result.m[7] = 0;
  2114. result.m[10] = -1.0 / (znear - zfar);
  2115. result.m[8] = result.m[9] = result.m[11] = 0;
  2116. result.m[12] = (left + right) / (left - right);
  2117. result.m[13] = (top + bottom) / (bottom - top);
  2118. result.m[14] = znear / (znear - zfar);
  2119. result.m[15] = 1.0;
  2120. };
  2121. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2122. var matrix = Matrix.Zero();
  2123. matrix.m[0] = (2.0 * znear) / width;
  2124. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2125. matrix.m[5] = (2.0 * znear) / height;
  2126. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2127. matrix.m[10] = -zfar / (znear - zfar);
  2128. matrix.m[8] = matrix.m[9] = 0.0;
  2129. matrix.m[11] = 1.0;
  2130. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2131. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2132. return matrix;
  2133. };
  2134. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2135. var matrix = Matrix.Zero();
  2136. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2137. return matrix;
  2138. };
  2139. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2140. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2141. var tan = 1.0 / (Math.tan(fov * 0.5));
  2142. if (isVerticalFovFixed) {
  2143. result.m[0] = tan / aspect;
  2144. }
  2145. else {
  2146. result.m[0] = tan;
  2147. }
  2148. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2149. if (isVerticalFovFixed) {
  2150. result.m[5] = tan;
  2151. }
  2152. else {
  2153. result.m[5] = tan * aspect;
  2154. }
  2155. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2156. result.m[8] = result.m[9] = 0.0;
  2157. result.m[10] = -zfar / (znear - zfar);
  2158. result.m[11] = 1.0;
  2159. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2160. result.m[14] = (znear * zfar) / (znear - zfar);
  2161. };
  2162. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2163. var cw = viewport.width;
  2164. var ch = viewport.height;
  2165. var cx = viewport.x;
  2166. var cy = viewport.y;
  2167. 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);
  2168. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2169. };
  2170. Matrix.GetAsMatrix2x2 = function (matrix) {
  2171. return new Float32Array([
  2172. matrix.m[0], matrix.m[1],
  2173. matrix.m[4], matrix.m[5]
  2174. ]);
  2175. };
  2176. Matrix.GetAsMatrix3x3 = function (matrix) {
  2177. return new Float32Array([
  2178. matrix.m[0], matrix.m[1], matrix.m[2],
  2179. matrix.m[4], matrix.m[5], matrix.m[6],
  2180. matrix.m[8], matrix.m[9], matrix.m[10]
  2181. ]);
  2182. };
  2183. Matrix.Transpose = function (matrix) {
  2184. var result = new Matrix();
  2185. result.m[0] = matrix.m[0];
  2186. result.m[1] = matrix.m[4];
  2187. result.m[2] = matrix.m[8];
  2188. result.m[3] = matrix.m[12];
  2189. result.m[4] = matrix.m[1];
  2190. result.m[5] = matrix.m[5];
  2191. result.m[6] = matrix.m[9];
  2192. result.m[7] = matrix.m[13];
  2193. result.m[8] = matrix.m[2];
  2194. result.m[9] = matrix.m[6];
  2195. result.m[10] = matrix.m[10];
  2196. result.m[11] = matrix.m[14];
  2197. result.m[12] = matrix.m[3];
  2198. result.m[13] = matrix.m[7];
  2199. result.m[14] = matrix.m[11];
  2200. result.m[15] = matrix.m[15];
  2201. return result;
  2202. };
  2203. Matrix.Reflection = function (plane) {
  2204. var matrix = new Matrix();
  2205. Matrix.ReflectionToRef(plane, matrix);
  2206. return matrix;
  2207. };
  2208. Matrix.ReflectionToRef = function (plane, result) {
  2209. plane.normalize();
  2210. var x = plane.normal.x;
  2211. var y = plane.normal.y;
  2212. var z = plane.normal.z;
  2213. var temp = -2 * x;
  2214. var temp2 = -2 * y;
  2215. var temp3 = -2 * z;
  2216. result.m[0] = (temp * x) + 1;
  2217. result.m[1] = temp2 * x;
  2218. result.m[2] = temp3 * x;
  2219. result.m[3] = 0.0;
  2220. result.m[4] = temp * y;
  2221. result.m[5] = (temp2 * y) + 1;
  2222. result.m[6] = temp3 * y;
  2223. result.m[7] = 0.0;
  2224. result.m[8] = temp * z;
  2225. result.m[9] = temp2 * z;
  2226. result.m[10] = (temp3 * z) + 1;
  2227. result.m[11] = 0.0;
  2228. result.m[12] = temp * plane.d;
  2229. result.m[13] = temp2 * plane.d;
  2230. result.m[14] = temp3 * plane.d;
  2231. result.m[15] = 1.0;
  2232. };
  2233. Matrix._tempQuaternion = new Quaternion();
  2234. Matrix._xAxis = Vector3.Zero();
  2235. Matrix._yAxis = Vector3.Zero();
  2236. Matrix._zAxis = Vector3.Zero();
  2237. return Matrix;
  2238. })();
  2239. BABYLON.Matrix = Matrix;
  2240. var Plane = (function () {
  2241. function Plane(a, b, c, d) {
  2242. this.normal = new Vector3(a, b, c);
  2243. this.d = d;
  2244. }
  2245. Plane.prototype.asArray = function () {
  2246. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2247. };
  2248. // Methods
  2249. Plane.prototype.clone = function () {
  2250. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2251. };
  2252. Plane.prototype.normalize = function () {
  2253. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2254. var magnitude = 0;
  2255. if (norm !== 0) {
  2256. magnitude = 1.0 / norm;
  2257. }
  2258. this.normal.x *= magnitude;
  2259. this.normal.y *= magnitude;
  2260. this.normal.z *= magnitude;
  2261. this.d *= magnitude;
  2262. return this;
  2263. };
  2264. Plane.prototype.transform = function (transformation) {
  2265. var transposedMatrix = Matrix.Transpose(transformation);
  2266. var x = this.normal.x;
  2267. var y = this.normal.y;
  2268. var z = this.normal.z;
  2269. var d = this.d;
  2270. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2271. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2272. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2273. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2274. return new Plane(normalX, normalY, normalZ, finalD);
  2275. };
  2276. Plane.prototype.dotCoordinate = function (point) {
  2277. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2278. };
  2279. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2280. var x1 = point2.x - point1.x;
  2281. var y1 = point2.y - point1.y;
  2282. var z1 = point2.z - point1.z;
  2283. var x2 = point3.x - point1.x;
  2284. var y2 = point3.y - point1.y;
  2285. var z2 = point3.z - point1.z;
  2286. var yz = (y1 * z2) - (z1 * y2);
  2287. var xz = (z1 * x2) - (x1 * z2);
  2288. var xy = (x1 * y2) - (y1 * x2);
  2289. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2290. var invPyth;
  2291. if (pyth !== 0) {
  2292. invPyth = 1.0 / pyth;
  2293. }
  2294. else {
  2295. invPyth = 0;
  2296. }
  2297. this.normal.x = yz * invPyth;
  2298. this.normal.y = xz * invPyth;
  2299. this.normal.z = xy * invPyth;
  2300. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2301. return this;
  2302. };
  2303. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2304. var dot = Vector3.Dot(this.normal, direction);
  2305. return (dot <= epsilon);
  2306. };
  2307. Plane.prototype.signedDistanceTo = function (point) {
  2308. return Vector3.Dot(point, this.normal) + this.d;
  2309. };
  2310. // Statics
  2311. Plane.FromArray = function (array) {
  2312. return new Plane(array[0], array[1], array[2], array[3]);
  2313. };
  2314. Plane.FromPoints = function (point1, point2, point3) {
  2315. var result = new Plane(0, 0, 0, 0);
  2316. result.copyFromPoints(point1, point2, point3);
  2317. return result;
  2318. };
  2319. Plane.FromPositionAndNormal = function (origin, normal) {
  2320. var result = new Plane(0, 0, 0, 0);
  2321. normal.normalize();
  2322. result.normal = normal;
  2323. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2324. return result;
  2325. };
  2326. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2327. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2328. return Vector3.Dot(point, normal) + d;
  2329. };
  2330. return Plane;
  2331. })();
  2332. BABYLON.Plane = Plane;
  2333. var Viewport = (function () {
  2334. function Viewport(x, y, width, height) {
  2335. this.x = x;
  2336. this.y = y;
  2337. this.width = width;
  2338. this.height = height;
  2339. }
  2340. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2341. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2342. };
  2343. return Viewport;
  2344. })();
  2345. BABYLON.Viewport = Viewport;
  2346. var Frustum = (function () {
  2347. function Frustum() {
  2348. }
  2349. Frustum.GetPlanes = function (transform) {
  2350. var frustumPlanes = [];
  2351. for (var index = 0; index < 6; index++) {
  2352. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2353. }
  2354. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2355. return frustumPlanes;
  2356. };
  2357. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2358. // Near
  2359. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2360. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2361. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2362. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2363. frustumPlanes[0].normalize();
  2364. // Far
  2365. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2366. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2367. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2368. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2369. frustumPlanes[1].normalize();
  2370. // Left
  2371. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2372. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2373. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2374. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2375. frustumPlanes[2].normalize();
  2376. // Right
  2377. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2378. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2379. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2380. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2381. frustumPlanes[3].normalize();
  2382. // Top
  2383. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2384. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2385. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2386. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2387. frustumPlanes[4].normalize();
  2388. // Bottom
  2389. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2390. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2391. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2392. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2393. frustumPlanes[5].normalize();
  2394. };
  2395. return Frustum;
  2396. })();
  2397. BABYLON.Frustum = Frustum;
  2398. (function (Space) {
  2399. Space[Space["LOCAL"] = 0] = "LOCAL";
  2400. Space[Space["WORLD"] = 1] = "WORLD";
  2401. })(BABYLON.Space || (BABYLON.Space = {}));
  2402. var Space = BABYLON.Space;
  2403. var Axis = (function () {
  2404. function Axis() {
  2405. }
  2406. Axis.X = new Vector3(1, 0, 0);
  2407. Axis.Y = new Vector3(0, 1, 0);
  2408. Axis.Z = new Vector3(0, 0, 1);
  2409. return Axis;
  2410. })();
  2411. BABYLON.Axis = Axis;
  2412. ;
  2413. var BezierCurve = (function () {
  2414. function BezierCurve() {
  2415. }
  2416. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2417. // Extract X (which is equal to time here)
  2418. var f0 = 1 - 3 * x2 + 3 * x1;
  2419. var f1 = 3 * x2 - 6 * x1;
  2420. var f2 = 3 * x1;
  2421. var refinedT = t;
  2422. for (var i = 0; i < 5; i++) {
  2423. var refinedT2 = refinedT * refinedT;
  2424. var refinedT3 = refinedT2 * refinedT;
  2425. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2426. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2427. refinedT -= (x - t) * slope;
  2428. refinedT = Math.min(1, Math.max(0, refinedT));
  2429. }
  2430. // Resolve cubic bezier for the given x
  2431. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2432. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2433. Math.pow(refinedT, 3);
  2434. };
  2435. return BezierCurve;
  2436. })();
  2437. BABYLON.BezierCurve = BezierCurve;
  2438. (function (Orientation) {
  2439. Orientation[Orientation["CW"] = 0] = "CW";
  2440. Orientation[Orientation["CCW"] = 1] = "CCW";
  2441. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2442. var Orientation = BABYLON.Orientation;
  2443. var Angle = (function () {
  2444. function Angle(radians) {
  2445. var _this = this;
  2446. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2447. this.radians = function () { return _this._radians; };
  2448. this._radians = radians;
  2449. if (this._radians < 0)
  2450. this._radians += (2 * Math.PI);
  2451. }
  2452. Angle.BetweenTwoPoints = function (a, b) {
  2453. var delta = b.subtract(a);
  2454. var theta = Math.atan2(delta.y, delta.x);
  2455. return new Angle(theta);
  2456. };
  2457. Angle.FromRadians = function (radians) {
  2458. return new Angle(radians);
  2459. };
  2460. Angle.FromDegrees = function (degrees) {
  2461. return new Angle(degrees * Math.PI / 180);
  2462. };
  2463. return Angle;
  2464. })();
  2465. BABYLON.Angle = Angle;
  2466. var Arc2 = (function () {
  2467. function Arc2(startPoint, midPoint, endPoint) {
  2468. this.startPoint = startPoint;
  2469. this.midPoint = midPoint;
  2470. this.endPoint = endPoint;
  2471. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2472. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2473. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2474. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2475. 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);
  2476. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2477. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2478. var a1 = this.startAngle.degrees();
  2479. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2480. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2481. // angles correction
  2482. if (a2 - a1 > +180.0)
  2483. a2 -= 360.0;
  2484. if (a2 - a1 < -180.0)
  2485. a2 += 360.0;
  2486. if (a3 - a2 > +180.0)
  2487. a3 -= 360.0;
  2488. if (a3 - a2 < -180.0)
  2489. a3 += 360.0;
  2490. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2491. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2492. }
  2493. return Arc2;
  2494. })();
  2495. BABYLON.Arc2 = Arc2;
  2496. var Path2 = (function () {
  2497. function Path2(x, y) {
  2498. this._points = new Array();
  2499. this._length = 0;
  2500. this.closed = false;
  2501. this._points.push(new Vector2(x, y));
  2502. }
  2503. Path2.prototype.addLineTo = function (x, y) {
  2504. if (closed) {
  2505. //Tools.Error("cannot add lines to closed paths");
  2506. return this;
  2507. }
  2508. var newPoint = new Vector2(x, y);
  2509. var previousPoint = this._points[this._points.length - 1];
  2510. this._points.push(newPoint);
  2511. this._length += newPoint.subtract(previousPoint).length();
  2512. return this;
  2513. };
  2514. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2515. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2516. if (closed) {
  2517. //Tools.Error("cannot add arcs to closed paths");
  2518. return this;
  2519. }
  2520. var startPoint = this._points[this._points.length - 1];
  2521. var midPoint = new Vector2(midX, midY);
  2522. var endPoint = new Vector2(endX, endY);
  2523. var arc = new Arc2(startPoint, midPoint, endPoint);
  2524. var increment = arc.angle.radians() / numberOfSegments;
  2525. if (arc.orientation === Orientation.CW)
  2526. increment *= -1;
  2527. var currentAngle = arc.startAngle.radians() + increment;
  2528. for (var i = 0; i < numberOfSegments; i++) {
  2529. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2530. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2531. this.addLineTo(x, y);
  2532. currentAngle += increment;
  2533. }
  2534. return this;
  2535. };
  2536. Path2.prototype.close = function () {
  2537. this.closed = true;
  2538. return this;
  2539. };
  2540. Path2.prototype.length = function () {
  2541. var result = this._length;
  2542. if (!this.closed) {
  2543. var lastPoint = this._points[this._points.length - 1];
  2544. var firstPoint = this._points[0];
  2545. result += (firstPoint.subtract(lastPoint).length());
  2546. }
  2547. return result;
  2548. };
  2549. Path2.prototype.getPoints = function () {
  2550. return this._points;
  2551. };
  2552. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2553. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2554. //Tools.Error("normalized length position should be between 0 and 1.");
  2555. return Vector2.Zero();
  2556. }
  2557. var lengthPosition = normalizedLengthPosition * this.length();
  2558. var previousOffset = 0;
  2559. for (var i = 0; i < this._points.length; i++) {
  2560. var j = (i + 1) % this._points.length;
  2561. var a = this._points[i];
  2562. var b = this._points[j];
  2563. var bToA = b.subtract(a);
  2564. var nextOffset = (bToA.length() + previousOffset);
  2565. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2566. var dir = bToA.normalize();
  2567. var localOffset = lengthPosition - previousOffset;
  2568. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2569. }
  2570. previousOffset = nextOffset;
  2571. }
  2572. //Tools.Error("internal error");
  2573. return Vector2.Zero();
  2574. };
  2575. Path2.StartingAt = function (x, y) {
  2576. return new Path2(x, y);
  2577. };
  2578. return Path2;
  2579. })();
  2580. BABYLON.Path2 = Path2;
  2581. var Path3D = (function () {
  2582. /**
  2583. * new Path3D(path, normal, raw)
  2584. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2585. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2586. * path : an array of Vector3, the curve axis of the Path3D
  2587. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2588. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2589. */
  2590. function Path3D(path, firstNormal, raw) {
  2591. this.path = path;
  2592. this._curve = new Array();
  2593. this._distances = new Array();
  2594. this._tangents = new Array();
  2595. this._normals = new Array();
  2596. this._binormals = new Array();
  2597. for (var p = 0; p < path.length; p++) {
  2598. this._curve[p] = path[p].clone(); // hard copy
  2599. }
  2600. this._raw = raw || false;
  2601. this._compute(firstNormal);
  2602. }
  2603. /**
  2604. * Returns the Path3D array of successive Vector3 designing its curve.
  2605. */
  2606. Path3D.prototype.getCurve = function () {
  2607. return this._curve;
  2608. };
  2609. /**
  2610. * Returns an array populated with tangent vectors on each Path3D curve point.
  2611. */
  2612. Path3D.prototype.getTangents = function () {
  2613. return this._tangents;
  2614. };
  2615. /**
  2616. * Returns an array populated with normal vectors on each Path3D curve point.
  2617. */
  2618. Path3D.prototype.getNormals = function () {
  2619. return this._normals;
  2620. };
  2621. /**
  2622. * Returns an array populated with binormal vectors on each Path3D curve point.
  2623. */
  2624. Path3D.prototype.getBinormals = function () {
  2625. return this._binormals;
  2626. };
  2627. /**
  2628. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2629. */
  2630. Path3D.prototype.getDistances = function () {
  2631. return this._distances;
  2632. };
  2633. /**
  2634. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2635. * Returns the same object updated.
  2636. */
  2637. Path3D.prototype.update = function (path, firstNormal) {
  2638. for (var p = 0; p < path.length; p++) {
  2639. this._curve[p].x = path[p].x;
  2640. this._curve[p].y = path[p].y;
  2641. this._curve[p].z = path[p].z;
  2642. }
  2643. this._compute(firstNormal);
  2644. return this;
  2645. };
  2646. // private function compute() : computes tangents, normals and binormals
  2647. Path3D.prototype._compute = function (firstNormal) {
  2648. var l = this._curve.length;
  2649. // first and last tangents
  2650. this._tangents[0] = this._getFirstNonNullVector(0);
  2651. if (!this._raw) {
  2652. this._tangents[0].normalize();
  2653. }
  2654. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2655. if (!this._raw) {
  2656. this._tangents[l - 1].normalize();
  2657. }
  2658. // normals and binormals at first point : arbitrary vector with _normalVector()
  2659. var tg0 = this._tangents[0];
  2660. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2661. this._normals[0] = pp0;
  2662. if (!this._raw) {
  2663. this._normals[0].normalize();
  2664. }
  2665. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2666. if (!this._raw) {
  2667. this._binormals[0].normalize();
  2668. }
  2669. this._distances[0] = 0;
  2670. // normals and binormals : next points
  2671. var prev; // previous vector (segment)
  2672. var cur; // current vector (segment)
  2673. var curTang; // current tangent
  2674. // previous normal
  2675. var prevBinor; // previous binormal
  2676. for (var i = 1; i < l; i++) {
  2677. // tangents
  2678. prev = this._getLastNonNullVector(i);
  2679. if (i < l - 1) {
  2680. cur = this._getFirstNonNullVector(i);
  2681. this._tangents[i] = prev.add(cur);
  2682. this._tangents[i].normalize();
  2683. }
  2684. this._distances[i] = this._distances[i - 1] + prev.length();
  2685. // normals and binormals
  2686. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2687. curTang = this._tangents[i];
  2688. prevBinor = this._binormals[i - 1];
  2689. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2690. if (!this._raw) {
  2691. this._normals[i].normalize();
  2692. }
  2693. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2694. if (!this._raw) {
  2695. this._binormals[i].normalize();
  2696. }
  2697. }
  2698. };
  2699. // private function getFirstNonNullVector(index)
  2700. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2701. Path3D.prototype._getFirstNonNullVector = function (index) {
  2702. var i = 1;
  2703. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2704. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2705. i++;
  2706. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2707. }
  2708. return nNVector;
  2709. };
  2710. // private function getLastNonNullVector(index)
  2711. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2712. Path3D.prototype._getLastNonNullVector = function (index) {
  2713. var i = 1;
  2714. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2715. while (nLVector.length() === 0 && index > i + 1) {
  2716. i++;
  2717. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2718. }
  2719. return nLVector;
  2720. };
  2721. // private function normalVector(v0, vt, va) :
  2722. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2723. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2724. Path3D.prototype._normalVector = function (v0, vt, va) {
  2725. var normal0;
  2726. if (va === undefined || va === null) {
  2727. var point;
  2728. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2729. point = new Vector3(0, -1, 0);
  2730. }
  2731. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2732. point = new Vector3(1, 0, 0);
  2733. }
  2734. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2735. point = new Vector3(0, 0, 1);
  2736. }
  2737. normal0 = Vector3.Cross(vt, point);
  2738. }
  2739. else {
  2740. normal0 = Vector3.Cross(vt, va);
  2741. Vector3.CrossToRef(normal0, vt, normal0);
  2742. }
  2743. normal0.normalize();
  2744. return normal0;
  2745. };
  2746. return Path3D;
  2747. })();
  2748. BABYLON.Path3D = Path3D;
  2749. var Curve3 = (function () {
  2750. /**
  2751. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2752. * A Curve3 is designed from a series of successive Vector3.
  2753. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2754. */
  2755. function Curve3(points) {
  2756. this._length = 0;
  2757. this._points = points;
  2758. this._length = this._computeLength(points);
  2759. }
  2760. /**
  2761. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2762. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2763. * @param v1 (Vector3) the control point
  2764. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2765. * @param nbPoints (integer) the wanted number of points in the curve
  2766. */
  2767. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2768. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2769. var bez = new Array();
  2770. var equation = function (t, val0, val1, val2) {
  2771. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2772. return res;
  2773. };
  2774. for (var i = 0; i <= nbPoints; i++) {
  2775. 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)));
  2776. }
  2777. return new Curve3(bez);
  2778. };
  2779. /**
  2780. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2781. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2782. * @param v1 (Vector3) the first control point
  2783. * @param v2 (Vector3) the second control point
  2784. * @param v3 (Vector3) the end point of the Cubic Bezier
  2785. * @param nbPoints (integer) the wanted number of points in the curve
  2786. */
  2787. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2788. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2789. var bez = new Array();
  2790. var equation = function (t, val0, val1, val2, val3) {
  2791. 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;
  2792. return res;
  2793. };
  2794. for (var i = 0; i <= nbPoints; i++) {
  2795. 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)));
  2796. }
  2797. return new Curve3(bez);
  2798. };
  2799. /**
  2800. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2801. * @param p1 (Vector3) the origin point of the Hermite Spline
  2802. * @param t1 (Vector3) the tangent vector at the origin point
  2803. * @param p2 (Vector3) the end point of the Hermite Spline
  2804. * @param t2 (Vector3) the tangent vector at the end point
  2805. * @param nbPoints (integer) the wanted number of points in the curve
  2806. */
  2807. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2808. var hermite = new Array();
  2809. var step = 1 / nbPoints;
  2810. for (var i = 0; i <= nbPoints; i++) {
  2811. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2812. }
  2813. return new Curve3(hermite);
  2814. };
  2815. /**
  2816. * Returns the Curve3 stored array of successive Vector3
  2817. */
  2818. Curve3.prototype.getPoints = function () {
  2819. return this._points;
  2820. };
  2821. /**
  2822. * Returns the computed length (float) of the curve.
  2823. */
  2824. Curve3.prototype.length = function () {
  2825. return this._length;
  2826. };
  2827. /**
  2828. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2829. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2830. * curveA and curveB keep unchanged.
  2831. */
  2832. Curve3.prototype.continue = function (curve) {
  2833. var lastPoint = this._points[this._points.length - 1];
  2834. var continuedPoints = this._points.slice();
  2835. var curvePoints = curve.getPoints();
  2836. for (var i = 1; i < curvePoints.length; i++) {
  2837. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2838. }
  2839. var continuedCurve = new Curve3(continuedPoints);
  2840. return continuedCurve;
  2841. };
  2842. Curve3.prototype._computeLength = function (path) {
  2843. var l = 0;
  2844. for (var i = 1; i < path.length; i++) {
  2845. l += (path[i].subtract(path[i - 1])).length();
  2846. }
  2847. return l;
  2848. };
  2849. return Curve3;
  2850. })();
  2851. BABYLON.Curve3 = Curve3;
  2852. // SphericalHarmonics
  2853. var SphericalHarmonics = (function () {
  2854. function SphericalHarmonics() {
  2855. this.L00 = Vector3.Zero();
  2856. this.L1_1 = Vector3.Zero();
  2857. this.L10 = Vector3.Zero();
  2858. this.L11 = Vector3.Zero();
  2859. this.L2_2 = Vector3.Zero();
  2860. this.L2_1 = Vector3.Zero();
  2861. this.L20 = Vector3.Zero();
  2862. this.L21 = Vector3.Zero();
  2863. this.L22 = Vector3.Zero();
  2864. }
  2865. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2866. var colorVector = new Vector3(color.r, color.g, color.b);
  2867. var c = colorVector.scale(deltaSolidAngle);
  2868. this.L00 = this.L00.add(c.scale(0.282095));
  2869. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2870. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2871. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2872. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2873. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2874. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2875. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2876. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2877. };
  2878. SphericalHarmonics.prototype.scale = function (scale) {
  2879. this.L00 = this.L00.scale(scale);
  2880. this.L1_1 = this.L1_1.scale(scale);
  2881. this.L10 = this.L10.scale(scale);
  2882. this.L11 = this.L11.scale(scale);
  2883. this.L2_2 = this.L2_2.scale(scale);
  2884. this.L2_1 = this.L2_1.scale(scale);
  2885. this.L20 = this.L20.scale(scale);
  2886. this.L21 = this.L21.scale(scale);
  2887. this.L22 = this.L22.scale(scale);
  2888. };
  2889. return SphericalHarmonics;
  2890. })();
  2891. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2892. // SphericalPolynomial
  2893. var SphericalPolynomial = (function () {
  2894. function SphericalPolynomial() {
  2895. this.x = Vector3.Zero();
  2896. this.y = Vector3.Zero();
  2897. this.z = Vector3.Zero();
  2898. this.xx = Vector3.Zero();
  2899. this.yy = Vector3.Zero();
  2900. this.zz = Vector3.Zero();
  2901. this.xy = Vector3.Zero();
  2902. this.yz = Vector3.Zero();
  2903. this.zx = Vector3.Zero();
  2904. }
  2905. SphericalPolynomial.prototype.addAmbient = function (color) {
  2906. var colorVector = new Vector3(color.r, color.g, color.b);
  2907. this.xx = this.xx.add(colorVector);
  2908. this.yy = this.yy.add(colorVector);
  2909. this.zz = this.zz.add(colorVector);
  2910. };
  2911. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2912. var result = new SphericalPolynomial();
  2913. result.x = harmonics.L11.scale(1.02333);
  2914. result.y = harmonics.L1_1.scale(1.02333);
  2915. result.z = harmonics.L10.scale(1.02333);
  2916. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2917. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2918. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2919. result.yz = harmonics.L2_1.scale(0.858086);
  2920. result.zx = harmonics.L21.scale(0.858086);
  2921. result.xy = harmonics.L2_2.scale(0.858086);
  2922. return result;
  2923. };
  2924. return SphericalPolynomial;
  2925. })();
  2926. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2927. // Vertex formats
  2928. var PositionNormalVertex = (function () {
  2929. function PositionNormalVertex(position, normal) {
  2930. if (position === void 0) { position = Vector3.Zero(); }
  2931. if (normal === void 0) { normal = Vector3.Up(); }
  2932. this.position = position;
  2933. this.normal = normal;
  2934. }
  2935. PositionNormalVertex.prototype.clone = function () {
  2936. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2937. };
  2938. return PositionNormalVertex;
  2939. })();
  2940. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2941. var PositionNormalTextureVertex = (function () {
  2942. function PositionNormalTextureVertex(position, normal, uv) {
  2943. if (position === void 0) { position = Vector3.Zero(); }
  2944. if (normal === void 0) { normal = Vector3.Up(); }
  2945. if (uv === void 0) { uv = Vector2.Zero(); }
  2946. this.position = position;
  2947. this.normal = normal;
  2948. this.uv = uv;
  2949. }
  2950. PositionNormalTextureVertex.prototype.clone = function () {
  2951. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2952. };
  2953. return PositionNormalTextureVertex;
  2954. })();
  2955. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2956. // Temporary pre-allocated objects for engine internal use
  2957. // usage in any internal function :
  2958. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2959. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2960. var Tmp = (function () {
  2961. function Tmp() {
  2962. }
  2963. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2964. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2965. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2966. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2967. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2968. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2969. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2970. Matrix.Zero(), Matrix.Zero(),
  2971. Matrix.Zero(), Matrix.Zero(),
  2972. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2973. return Tmp;
  2974. })();
  2975. BABYLON.Tmp = Tmp;
  2976. })(BABYLON || (BABYLON = {}));
  2977. var BABYLON;
  2978. (function (BABYLON) {
  2979. function generateSerializableMember(type, sourceName) {
  2980. return function (target, propertyKey) {
  2981. if (!target.__serializableMembers) {
  2982. target.__serializableMembers = {};
  2983. }
  2984. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2985. };
  2986. }
  2987. function serialize(sourceName) {
  2988. return generateSerializableMember(0, sourceName); // value member
  2989. }
  2990. BABYLON.serialize = serialize;
  2991. function serializeAsTexture(sourceName) {
  2992. return generateSerializableMember(1, sourceName); // texture member
  2993. }
  2994. BABYLON.serializeAsTexture = serializeAsTexture;
  2995. function serializeAsColor3(sourceName) {
  2996. return generateSerializableMember(2, sourceName); // color3 member
  2997. }
  2998. BABYLON.serializeAsColor3 = serializeAsColor3;
  2999. function serializeAsFresnelParameters(sourceName) {
  3000. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3001. }
  3002. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3003. function serializeAsVector2(sourceName) {
  3004. return generateSerializableMember(4, sourceName); // vector2 member
  3005. }
  3006. BABYLON.serializeAsVector2 = serializeAsVector2;
  3007. function serializeAsVector3(sourceName) {
  3008. return generateSerializableMember(5, sourceName); // vector3 member
  3009. }
  3010. BABYLON.serializeAsVector3 = serializeAsVector3;
  3011. function serializeAsMeshReference(sourceName) {
  3012. return generateSerializableMember(6, sourceName); // mesh reference member
  3013. }
  3014. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3015. var SerializationHelper = (function () {
  3016. function SerializationHelper() {
  3017. }
  3018. SerializationHelper.Serialize = function (entity, serializationObject) {
  3019. if (!serializationObject) {
  3020. serializationObject = {};
  3021. }
  3022. // Tags
  3023. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3024. // Properties
  3025. for (var property in entity.__serializableMembers) {
  3026. var propertyDescriptor = entity.__serializableMembers[property];
  3027. var targetPropertyName = propertyDescriptor.sourceName || property;
  3028. var propertyType = propertyDescriptor.type;
  3029. var sourceProperty = entity[property];
  3030. if (sourceProperty !== undefined && sourceProperty !== null) {
  3031. switch (propertyType) {
  3032. case 0:
  3033. serializationObject[targetPropertyName] = sourceProperty;
  3034. break;
  3035. case 1:
  3036. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3037. break;
  3038. case 2:
  3039. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3040. break;
  3041. case 3:
  3042. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3043. break;
  3044. case 4:
  3045. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3046. break;
  3047. case 5:
  3048. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3049. break;
  3050. case 6:
  3051. serializationObject[targetPropertyName] = sourceProperty.id;
  3052. break;
  3053. }
  3054. }
  3055. }
  3056. return serializationObject;
  3057. };
  3058. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3059. var destination = creationFunction();
  3060. // Tags
  3061. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3062. // Properties
  3063. for (var property in destination.__serializableMembers) {
  3064. var propertyDescriptor = destination.__serializableMembers[property];
  3065. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3066. var propertyType = propertyDescriptor.type;
  3067. if (sourceProperty !== undefined && sourceProperty !== null) {
  3068. switch (propertyType) {
  3069. case 0:
  3070. destination[property] = sourceProperty;
  3071. break;
  3072. case 1:
  3073. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3074. break;
  3075. case 2:
  3076. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3077. break;
  3078. case 3:
  3079. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3080. break;
  3081. case 4:
  3082. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3083. break;
  3084. case 5:
  3085. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3086. break;
  3087. case 6:
  3088. destination[property] = scene.getLastMeshByID(sourceProperty);
  3089. break;
  3090. }
  3091. }
  3092. }
  3093. return destination;
  3094. };
  3095. SerializationHelper.Clone = function (creationFunction, source) {
  3096. var destination = creationFunction();
  3097. // Tags
  3098. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3099. // Properties
  3100. for (var property in destination.__serializableMembers) {
  3101. var propertyDescriptor = destination.__serializableMembers[property];
  3102. var sourceProperty = source[property];
  3103. var propertyType = propertyDescriptor.type;
  3104. if (sourceProperty !== undefined && sourceProperty !== null) {
  3105. switch (propertyType) {
  3106. case 0: // Value
  3107. case 6:
  3108. destination[property] = sourceProperty;
  3109. break;
  3110. case 1: // Texture
  3111. case 2: // Color3
  3112. case 3: // FresnelParameters
  3113. case 4: // Vector2
  3114. case 5:
  3115. destination[property] = sourceProperty.clone();
  3116. break;
  3117. }
  3118. }
  3119. }
  3120. return destination;
  3121. };
  3122. return SerializationHelper;
  3123. })();
  3124. BABYLON.SerializationHelper = SerializationHelper;
  3125. })(BABYLON || (BABYLON = {}));
  3126. var BABYLON;
  3127. (function (BABYLON) {
  3128. /**
  3129. * A class serves as a medium between the observable and its observers
  3130. */
  3131. var EventState = (function () {
  3132. /**
  3133. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3134. */
  3135. function EventState(skipNextObservers) {
  3136. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3137. this.skipNextObservers = skipNextObservers;
  3138. }
  3139. return EventState;
  3140. })();
  3141. BABYLON.EventState = EventState;
  3142. var Observer = (function () {
  3143. function Observer(callback, mask) {
  3144. this.callback = callback;
  3145. this.mask = mask;
  3146. }
  3147. return Observer;
  3148. })();
  3149. BABYLON.Observer = Observer;
  3150. var Observable = (function () {
  3151. function Observable() {
  3152. this._observers = new Array();
  3153. }
  3154. /**
  3155. * Create a new Observer with the specified callback
  3156. * @param callback the callback that will be executed for that Observer
  3157. * @param mash the mask used to filter observers
  3158. * @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.
  3159. */
  3160. Observable.prototype.add = function (callback, mask, insertFirst) {
  3161. if (mask === void 0) { mask = -1; }
  3162. if (insertFirst === void 0) { insertFirst = false; }
  3163. if (!callback) {
  3164. return null;
  3165. }
  3166. var observer = new Observer(callback, mask);
  3167. if (insertFirst) {
  3168. this._observers.unshift(observer);
  3169. }
  3170. else {
  3171. this._observers.push(observer);
  3172. }
  3173. return observer;
  3174. };
  3175. /**
  3176. * Remove an Observer from the Observable object
  3177. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3178. */
  3179. Observable.prototype.remove = function (observer) {
  3180. var index = this._observers.indexOf(observer);
  3181. if (index !== -1) {
  3182. this._observers.splice(index, 1);
  3183. return true;
  3184. }
  3185. return false;
  3186. };
  3187. /**
  3188. * Remove a callback from the Observable object
  3189. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3190. */
  3191. Observable.prototype.removeCallback = function (callback) {
  3192. for (var index = 0; index < this._observers.length; index++) {
  3193. if (this._observers[index].callback === callback) {
  3194. this._observers.splice(index, 1);
  3195. return true;
  3196. }
  3197. }
  3198. return false;
  3199. };
  3200. /**
  3201. * Notify all Observers by calling their respective callback with the given data
  3202. * @param eventData
  3203. * @param mask
  3204. */
  3205. Observable.prototype.notifyObservers = function (eventData, mask) {
  3206. if (mask === void 0) { mask = -1; }
  3207. var state = new EventState();
  3208. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3209. var obs = _a[_i];
  3210. if (obs.mask & mask) {
  3211. obs.callback(eventData, state);
  3212. }
  3213. if (state.skipNextObservers) {
  3214. break;
  3215. }
  3216. }
  3217. };
  3218. /**
  3219. * return true is the Observable has at least one Observer registered
  3220. */
  3221. Observable.prototype.hasObservers = function () {
  3222. return this._observers.length > 0;
  3223. };
  3224. /**
  3225. * Clear the list of observers
  3226. */
  3227. Observable.prototype.clear = function () {
  3228. this._observers = new Array();
  3229. };
  3230. /**
  3231. * Clone the current observable
  3232. */
  3233. Observable.prototype.clone = function () {
  3234. var result = new Observable();
  3235. result._observers = this._observers.slice(0);
  3236. return result;
  3237. };
  3238. return Observable;
  3239. })();
  3240. BABYLON.Observable = Observable;
  3241. })(BABYLON || (BABYLON = {}));
  3242. var BABYLON;
  3243. (function (BABYLON) {
  3244. var Database = (function () {
  3245. function Database(urlToScene, callbackManifestChecked) {
  3246. // Handling various flavors of prefixed version of IndexedDB
  3247. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3248. this.callbackManifestChecked = callbackManifestChecked;
  3249. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3250. this.db = null;
  3251. this.enableSceneOffline = false;
  3252. this.enableTexturesOffline = false;
  3253. this.manifestVersionFound = 0;
  3254. this.mustUpdateRessources = false;
  3255. this.hasReachedQuota = false;
  3256. if (!Database.IDBStorageEnabled) {
  3257. this.callbackManifestChecked(true);
  3258. }
  3259. else {
  3260. this.checkManifestFile();
  3261. }
  3262. }
  3263. Database.prototype.checkManifestFile = function () {
  3264. var _this = this;
  3265. function noManifestFile() {
  3266. that.enableSceneOffline = false;
  3267. that.enableTexturesOffline = false;
  3268. that.callbackManifestChecked(false);
  3269. }
  3270. var that = this;
  3271. var timeStampUsed = false;
  3272. var manifestURL = this.currentSceneUrl + ".manifest";
  3273. var xhr = new XMLHttpRequest();
  3274. if (navigator.onLine) {
  3275. // Adding a timestamp to by-pass browsers' cache
  3276. timeStampUsed = true;
  3277. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3278. }
  3279. xhr.open("GET", manifestURL, true);
  3280. xhr.addEventListener("load", function () {
  3281. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3282. try {
  3283. var manifestFile = JSON.parse(xhr.response);
  3284. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3285. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3286. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3287. _this.manifestVersionFound = manifestFile.version;
  3288. }
  3289. if (_this.callbackManifestChecked) {
  3290. _this.callbackManifestChecked(true);
  3291. }
  3292. }
  3293. catch (ex) {
  3294. noManifestFile();
  3295. }
  3296. }
  3297. else {
  3298. noManifestFile();
  3299. }
  3300. }, false);
  3301. xhr.addEventListener("error", function (event) {
  3302. if (timeStampUsed) {
  3303. timeStampUsed = false;
  3304. // Let's retry without the timeStamp
  3305. // It could fail when coupled with HTML5 Offline API
  3306. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3307. xhr.open("GET", retryManifestURL, true);
  3308. xhr.send();
  3309. }
  3310. else {
  3311. noManifestFile();
  3312. }
  3313. }, false);
  3314. try {
  3315. xhr.send();
  3316. }
  3317. catch (ex) {
  3318. BABYLON.Tools.Error("Error on XHR send request.");
  3319. that.callbackManifestChecked(false);
  3320. }
  3321. };
  3322. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3323. var _this = this;
  3324. function handleError() {
  3325. that.isSupported = false;
  3326. if (errorCallback)
  3327. errorCallback();
  3328. }
  3329. var that = this;
  3330. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3331. // Your browser doesn't support IndexedDB
  3332. this.isSupported = false;
  3333. if (errorCallback)
  3334. errorCallback();
  3335. }
  3336. else {
  3337. // If the DB hasn't been opened or created yet
  3338. if (!this.db) {
  3339. this.hasReachedQuota = false;
  3340. this.isSupported = true;
  3341. var request = this.idbFactory.open("babylonjs", 1);
  3342. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3343. request.onerror = function (event) {
  3344. handleError();
  3345. };
  3346. // executes when a version change transaction cannot complete due to other active transactions
  3347. request.onblocked = function (event) {
  3348. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3349. handleError();
  3350. };
  3351. // DB has been opened successfully
  3352. request.onsuccess = function (event) {
  3353. _this.db = request.result;
  3354. successCallback();
  3355. };
  3356. // Initialization of the DB. Creating Scenes & Textures stores
  3357. request.onupgradeneeded = function (event) {
  3358. _this.db = (event.target).result;
  3359. try {
  3360. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3361. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3362. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3363. }
  3364. catch (ex) {
  3365. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3366. handleError();
  3367. }
  3368. };
  3369. }
  3370. else {
  3371. if (successCallback)
  3372. successCallback();
  3373. }
  3374. }
  3375. };
  3376. Database.prototype.loadImageFromDB = function (url, image) {
  3377. var _this = this;
  3378. var completeURL = Database.ReturnFullUrlLocation(url);
  3379. var saveAndLoadImage = function () {
  3380. if (!_this.hasReachedQuota && _this.db !== null) {
  3381. // the texture is not yet in the DB, let's try to save it
  3382. _this._saveImageIntoDBAsync(completeURL, image);
  3383. }
  3384. else {
  3385. image.src = url;
  3386. }
  3387. };
  3388. if (!this.mustUpdateRessources) {
  3389. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3390. }
  3391. else {
  3392. saveAndLoadImage();
  3393. }
  3394. };
  3395. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3396. if (this.isSupported && this.db !== null) {
  3397. var texture;
  3398. var transaction = this.db.transaction(["textures"]);
  3399. transaction.onabort = function (event) {
  3400. image.src = url;
  3401. };
  3402. transaction.oncomplete = function (event) {
  3403. var blobTextureURL;
  3404. if (texture) {
  3405. var URL = window.URL || window.webkitURL;
  3406. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3407. image.onerror = function () {
  3408. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3409. image.src = url;
  3410. };
  3411. image.src = blobTextureURL;
  3412. }
  3413. else {
  3414. notInDBCallback();
  3415. }
  3416. };
  3417. var getRequest = transaction.objectStore("textures").get(url);
  3418. getRequest.onsuccess = function (event) {
  3419. texture = (event.target).result;
  3420. };
  3421. getRequest.onerror = function (event) {
  3422. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3423. image.src = url;
  3424. };
  3425. }
  3426. else {
  3427. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3428. image.src = url;
  3429. }
  3430. };
  3431. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3432. var _this = this;
  3433. if (this.isSupported) {
  3434. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3435. var generateBlobUrl = function () {
  3436. var blobTextureURL;
  3437. if (blob) {
  3438. var URL = window.URL || window.webkitURL;
  3439. try {
  3440. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3441. }
  3442. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3443. catch (ex) {
  3444. blobTextureURL = URL.createObjectURL(blob);
  3445. }
  3446. }
  3447. image.src = blobTextureURL;
  3448. };
  3449. if (Database.IsUASupportingBlobStorage) {
  3450. var xhr = new XMLHttpRequest(), blob;
  3451. xhr.open("GET", url, true);
  3452. xhr.responseType = "blob";
  3453. xhr.addEventListener("load", function () {
  3454. if (xhr.status === 200) {
  3455. // Blob as response (XHR2)
  3456. blob = xhr.response;
  3457. var transaction = _this.db.transaction(["textures"], "readwrite");
  3458. // the transaction could abort because of a QuotaExceededError error
  3459. transaction.onabort = function (event) {
  3460. try {
  3461. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3462. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3463. this.hasReachedQuota = true;
  3464. }
  3465. }
  3466. catch (ex) { }
  3467. generateBlobUrl();
  3468. };
  3469. transaction.oncomplete = function (event) {
  3470. generateBlobUrl();
  3471. };
  3472. var newTexture = { textureUrl: url, data: blob };
  3473. try {
  3474. // Put the blob into the dabase
  3475. var addRequest = transaction.objectStore("textures").put(newTexture);
  3476. addRequest.onsuccess = function (event) {
  3477. };
  3478. addRequest.onerror = function (event) {
  3479. generateBlobUrl();
  3480. };
  3481. }
  3482. catch (ex) {
  3483. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3484. if (ex.code === 25) {
  3485. Database.IsUASupportingBlobStorage = false;
  3486. }
  3487. image.src = url;
  3488. }
  3489. }
  3490. else {
  3491. image.src = url;
  3492. }
  3493. }, false);
  3494. xhr.addEventListener("error", function (event) {
  3495. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3496. image.src = url;
  3497. }, false);
  3498. xhr.send();
  3499. }
  3500. else {
  3501. image.src = url;
  3502. }
  3503. }
  3504. else {
  3505. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3506. image.src = url;
  3507. }
  3508. };
  3509. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3510. var _this = this;
  3511. var updateVersion = function (event) {
  3512. // the version is not yet in the DB or we need to update it
  3513. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3514. };
  3515. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3516. };
  3517. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3518. var _this = this;
  3519. if (this.isSupported) {
  3520. var version;
  3521. try {
  3522. var transaction = this.db.transaction(["versions"]);
  3523. transaction.oncomplete = function (event) {
  3524. if (version) {
  3525. // If the version in the JSON file is > than the version in DB
  3526. if (_this.manifestVersionFound > version.data) {
  3527. _this.mustUpdateRessources = true;
  3528. updateInDBCallback();
  3529. }
  3530. else {
  3531. callback(version.data);
  3532. }
  3533. }
  3534. else {
  3535. _this.mustUpdateRessources = true;
  3536. updateInDBCallback();
  3537. }
  3538. };
  3539. transaction.onabort = function (event) {
  3540. callback(-1);
  3541. };
  3542. var getRequest = transaction.objectStore("versions").get(url);
  3543. getRequest.onsuccess = function (event) {
  3544. version = (event.target).result;
  3545. };
  3546. getRequest.onerror = function (event) {
  3547. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3548. callback(-1);
  3549. };
  3550. }
  3551. catch (ex) {
  3552. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3553. callback(-1);
  3554. }
  3555. }
  3556. else {
  3557. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3558. callback(-1);
  3559. }
  3560. };
  3561. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3562. var _this = this;
  3563. if (this.isSupported && !this.hasReachedQuota) {
  3564. try {
  3565. // Open a transaction to the database
  3566. var transaction = this.db.transaction(["versions"], "readwrite");
  3567. // the transaction could abort because of a QuotaExceededError error
  3568. transaction.onabort = function (event) {
  3569. try {
  3570. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3571. _this.hasReachedQuota = true;
  3572. }
  3573. }
  3574. catch (ex) { }
  3575. callback(-1);
  3576. };
  3577. transaction.oncomplete = function (event) {
  3578. callback(_this.manifestVersionFound);
  3579. };
  3580. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3581. // Put the scene into the database
  3582. var addRequest = transaction.objectStore("versions").put(newVersion);
  3583. addRequest.onsuccess = function (event) {
  3584. };
  3585. addRequest.onerror = function (event) {
  3586. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3587. };
  3588. }
  3589. catch (ex) {
  3590. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3591. callback(-1);
  3592. }
  3593. }
  3594. else {
  3595. callback(-1);
  3596. }
  3597. };
  3598. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3599. var _this = this;
  3600. var completeUrl = Database.ReturnFullUrlLocation(url);
  3601. var saveAndLoadFile = function (event) {
  3602. // the scene is not yet in the DB, let's try to save it
  3603. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3604. };
  3605. this._checkVersionFromDB(completeUrl, function (version) {
  3606. if (version !== -1) {
  3607. if (!_this.mustUpdateRessources) {
  3608. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3609. }
  3610. else {
  3611. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3612. }
  3613. }
  3614. else {
  3615. errorCallback();
  3616. }
  3617. });
  3618. };
  3619. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3620. if (this.isSupported) {
  3621. var targetStore;
  3622. if (url.indexOf(".babylon") !== -1) {
  3623. targetStore = "scenes";
  3624. }
  3625. else {
  3626. targetStore = "textures";
  3627. }
  3628. var file;
  3629. var transaction = this.db.transaction([targetStore]);
  3630. transaction.oncomplete = function (event) {
  3631. if (file) {
  3632. callback(file.data);
  3633. }
  3634. else {
  3635. notInDBCallback();
  3636. }
  3637. };
  3638. transaction.onabort = function (event) {
  3639. notInDBCallback();
  3640. };
  3641. var getRequest = transaction.objectStore(targetStore).get(url);
  3642. getRequest.onsuccess = function (event) {
  3643. file = (event.target).result;
  3644. };
  3645. getRequest.onerror = function (event) {
  3646. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3647. notInDBCallback();
  3648. };
  3649. }
  3650. else {
  3651. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3652. callback();
  3653. }
  3654. };
  3655. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3656. var _this = this;
  3657. if (this.isSupported) {
  3658. var targetStore;
  3659. if (url.indexOf(".babylon") !== -1) {
  3660. targetStore = "scenes";
  3661. }
  3662. else {
  3663. targetStore = "textures";
  3664. }
  3665. // Create XHR
  3666. var xhr = new XMLHttpRequest(), fileData;
  3667. xhr.open("GET", url, true);
  3668. if (useArrayBuffer) {
  3669. xhr.responseType = "arraybuffer";
  3670. }
  3671. xhr.onprogress = progressCallback;
  3672. xhr.addEventListener("load", function () {
  3673. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3674. // Blob as response (XHR2)
  3675. //fileData = xhr.responseText;
  3676. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3677. if (!_this.hasReachedQuota) {
  3678. // Open a transaction to the database
  3679. var transaction = _this.db.transaction([targetStore], "readwrite");
  3680. // the transaction could abort because of a QuotaExceededError error
  3681. transaction.onabort = function (event) {
  3682. try {
  3683. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3684. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3685. this.hasReachedQuota = true;
  3686. }
  3687. }
  3688. catch (ex) { }
  3689. callback(fileData);
  3690. };
  3691. transaction.oncomplete = function (event) {
  3692. callback(fileData);
  3693. };
  3694. var newFile;
  3695. if (targetStore === "scenes") {
  3696. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3697. }
  3698. else {
  3699. newFile = { textureUrl: url, data: fileData };
  3700. }
  3701. try {
  3702. // Put the scene into the database
  3703. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3704. addRequest.onsuccess = function (event) {
  3705. };
  3706. addRequest.onerror = function (event) {
  3707. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3708. };
  3709. }
  3710. catch (ex) {
  3711. callback(fileData);
  3712. }
  3713. }
  3714. else {
  3715. callback(fileData);
  3716. }
  3717. }
  3718. else {
  3719. callback();
  3720. }
  3721. }, false);
  3722. xhr.addEventListener("error", function (event) {
  3723. BABYLON.Tools.Error("error on XHR request.");
  3724. callback();
  3725. }, false);
  3726. xhr.send();
  3727. }
  3728. else {
  3729. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3730. callback();
  3731. }
  3732. };
  3733. Database.IsUASupportingBlobStorage = true;
  3734. Database.IDBStorageEnabled = true;
  3735. Database.parseURL = function (url) {
  3736. var a = document.createElement('a');
  3737. a.href = url;
  3738. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3739. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3740. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3741. return absLocation;
  3742. };
  3743. Database.ReturnFullUrlLocation = function (url) {
  3744. if (url.indexOf("http:/") === -1) {
  3745. return (Database.parseURL(window.location.href) + url);
  3746. }
  3747. else {
  3748. return url;
  3749. }
  3750. };
  3751. return Database;
  3752. })();
  3753. BABYLON.Database = Database;
  3754. })(BABYLON || (BABYLON = {}));
  3755. var BABYLON;
  3756. (function (BABYLON) {
  3757. var Internals;
  3758. (function (Internals) {
  3759. /*
  3760. * Based on jsTGALoader - Javascript loader for TGA file
  3761. * By Vincent Thibault
  3762. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3763. */
  3764. var TGATools = (function () {
  3765. function TGATools() {
  3766. }
  3767. TGATools.GetTGAHeader = function (data) {
  3768. var offset = 0;
  3769. var header = {
  3770. id_length: data[offset++],
  3771. colormap_type: data[offset++],
  3772. image_type: data[offset++],
  3773. colormap_index: data[offset++] | data[offset++] << 8,
  3774. colormap_length: data[offset++] | data[offset++] << 8,
  3775. colormap_size: data[offset++],
  3776. origin: [
  3777. data[offset++] | data[offset++] << 8,
  3778. data[offset++] | data[offset++] << 8
  3779. ],
  3780. width: data[offset++] | data[offset++] << 8,
  3781. height: data[offset++] | data[offset++] << 8,
  3782. pixel_size: data[offset++],
  3783. flags: data[offset++]
  3784. };
  3785. return header;
  3786. };
  3787. TGATools.UploadContent = function (gl, data) {
  3788. // Not enough data to contain header ?
  3789. if (data.length < 19) {
  3790. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3791. return;
  3792. }
  3793. // Read Header
  3794. var offset = 18;
  3795. var header = TGATools.GetTGAHeader(data);
  3796. // Assume it's a valid Targa file.
  3797. if (header.id_length + offset > data.length) {
  3798. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3799. return;
  3800. }
  3801. // Skip not needed data
  3802. offset += header.id_length;
  3803. var use_rle = false;
  3804. var use_pal = false;
  3805. var use_rgb = false;
  3806. var use_grey = false;
  3807. // Get some informations.
  3808. switch (header.image_type) {
  3809. case TGATools._TYPE_RLE_INDEXED:
  3810. use_rle = true;
  3811. case TGATools._TYPE_INDEXED:
  3812. use_pal = true;
  3813. break;
  3814. case TGATools._TYPE_RLE_RGB:
  3815. use_rle = true;
  3816. case TGATools._TYPE_RGB:
  3817. use_rgb = true;
  3818. break;
  3819. case TGATools._TYPE_RLE_GREY:
  3820. use_rle = true;
  3821. case TGATools._TYPE_GREY:
  3822. use_grey = true;
  3823. break;
  3824. }
  3825. var pixel_data;
  3826. var numAlphaBits = header.flags & 0xf;
  3827. var pixel_size = header.pixel_size >> 3;
  3828. var pixel_total = header.width * header.height * pixel_size;
  3829. // Read palettes
  3830. var palettes;
  3831. if (use_pal) {
  3832. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3833. }
  3834. // Read LRE
  3835. if (use_rle) {
  3836. pixel_data = new Uint8Array(pixel_total);
  3837. var c, count, i;
  3838. var localOffset = 0;
  3839. var pixels = new Uint8Array(pixel_size);
  3840. while (offset < pixel_total && localOffset < pixel_total) {
  3841. c = data[offset++];
  3842. count = (c & 0x7f) + 1;
  3843. // RLE pixels
  3844. if (c & 0x80) {
  3845. // Bind pixel tmp array
  3846. for (i = 0; i < pixel_size; ++i) {
  3847. pixels[i] = data[offset++];
  3848. }
  3849. // Copy pixel array
  3850. for (i = 0; i < count; ++i) {
  3851. pixel_data.set(pixels, localOffset + i * pixel_size);
  3852. }
  3853. localOffset += pixel_size * count;
  3854. }
  3855. else {
  3856. count *= pixel_size;
  3857. for (i = 0; i < count; ++i) {
  3858. pixel_data[localOffset + i] = data[offset++];
  3859. }
  3860. localOffset += count;
  3861. }
  3862. }
  3863. }
  3864. else {
  3865. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3866. }
  3867. // Load to texture
  3868. var x_start, y_start, x_step, y_step, y_end, x_end;
  3869. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3870. default:
  3871. case TGATools._ORIGIN_UL:
  3872. x_start = 0;
  3873. x_step = 1;
  3874. x_end = header.width;
  3875. y_start = 0;
  3876. y_step = 1;
  3877. y_end = header.height;
  3878. break;
  3879. case TGATools._ORIGIN_BL:
  3880. x_start = 0;
  3881. x_step = 1;
  3882. x_end = header.width;
  3883. y_start = header.height - 1;
  3884. y_step = -1;
  3885. y_end = -1;
  3886. break;
  3887. case TGATools._ORIGIN_UR:
  3888. x_start = header.width - 1;
  3889. x_step = -1;
  3890. x_end = -1;
  3891. y_start = 0;
  3892. y_step = 1;
  3893. y_end = header.height;
  3894. break;
  3895. case TGATools._ORIGIN_BR:
  3896. x_start = header.width - 1;
  3897. x_step = -1;
  3898. x_end = -1;
  3899. y_start = header.height - 1;
  3900. y_step = -1;
  3901. y_end = -1;
  3902. break;
  3903. }
  3904. // Load the specify method
  3905. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3906. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3907. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3908. };
  3909. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3910. var image = pixel_data, colormap = palettes;
  3911. var width = header.width, height = header.height;
  3912. var color, i = 0, x, y;
  3913. var imageData = new Uint8Array(width * height * 4);
  3914. for (y = y_start; y !== y_end; y += y_step) {
  3915. for (x = x_start; x !== x_end; x += x_step, i++) {
  3916. color = image[i];
  3917. imageData[(x + width * y) * 4 + 3] = 255;
  3918. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3919. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3920. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3921. }
  3922. }
  3923. return imageData;
  3924. };
  3925. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3926. var image = pixel_data;
  3927. var width = header.width, height = header.height;
  3928. var color, i = 0, x, y;
  3929. var imageData = new Uint8Array(width * height * 4);
  3930. for (y = y_start; y !== y_end; y += y_step) {
  3931. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3932. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3933. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3934. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3935. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3936. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3937. }
  3938. }
  3939. return imageData;
  3940. };
  3941. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3942. var image = pixel_data;
  3943. var width = header.width, height = header.height;
  3944. var i = 0, x, y;
  3945. var imageData = new Uint8Array(width * height * 4);
  3946. for (y = y_start; y !== y_end; y += y_step) {
  3947. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3948. imageData[(x + width * y) * 4 + 3] = 255;
  3949. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3950. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3951. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3952. }
  3953. }
  3954. return imageData;
  3955. };
  3956. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3957. var image = pixel_data;
  3958. var width = header.width, height = header.height;
  3959. var i = 0, x, y;
  3960. var imageData = new Uint8Array(width * height * 4);
  3961. for (y = y_start; y !== y_end; y += y_step) {
  3962. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3963. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3964. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3965. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3966. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3967. }
  3968. }
  3969. return imageData;
  3970. };
  3971. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3972. var image = pixel_data;
  3973. var width = header.width, height = header.height;
  3974. var color, i = 0, x, y;
  3975. var imageData = new Uint8Array(width * height * 4);
  3976. for (y = y_start; y !== y_end; y += y_step) {
  3977. for (x = x_start; x !== x_end; x += x_step, i++) {
  3978. color = image[i];
  3979. imageData[(x + width * y) * 4 + 0] = color;
  3980. imageData[(x + width * y) * 4 + 1] = color;
  3981. imageData[(x + width * y) * 4 + 2] = color;
  3982. imageData[(x + width * y) * 4 + 3] = 255;
  3983. }
  3984. }
  3985. return imageData;
  3986. };
  3987. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3988. var image = pixel_data;
  3989. var width = header.width, height = header.height;
  3990. var i = 0, x, y;
  3991. var imageData = new Uint8Array(width * height * 4);
  3992. for (y = y_start; y !== y_end; y += y_step) {
  3993. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3994. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3995. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3996. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3997. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3998. }
  3999. }
  4000. return imageData;
  4001. };
  4002. TGATools._TYPE_NO_DATA = 0;
  4003. TGATools._TYPE_INDEXED = 1;
  4004. TGATools._TYPE_RGB = 2;
  4005. TGATools._TYPE_GREY = 3;
  4006. TGATools._TYPE_RLE_INDEXED = 9;
  4007. TGATools._TYPE_RLE_RGB = 10;
  4008. TGATools._TYPE_RLE_GREY = 11;
  4009. TGATools._ORIGIN_MASK = 0x30;
  4010. TGATools._ORIGIN_SHIFT = 0x04;
  4011. TGATools._ORIGIN_BL = 0x00;
  4012. TGATools._ORIGIN_BR = 0x01;
  4013. TGATools._ORIGIN_UL = 0x02;
  4014. TGATools._ORIGIN_UR = 0x03;
  4015. return TGATools;
  4016. })();
  4017. Internals.TGATools = TGATools;
  4018. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4019. })(BABYLON || (BABYLON = {}));
  4020. var BABYLON;
  4021. (function (BABYLON) {
  4022. var SmartArray = (function () {
  4023. function SmartArray(capacity) {
  4024. this.length = 0;
  4025. this._duplicateId = 0;
  4026. this.data = new Array(capacity);
  4027. this._id = SmartArray._GlobalId++;
  4028. }
  4029. SmartArray.prototype.push = function (value) {
  4030. this.data[this.length++] = value;
  4031. if (this.length > this.data.length) {
  4032. this.data.length *= 2;
  4033. }
  4034. if (!value.__smartArrayFlags) {
  4035. value.__smartArrayFlags = {};
  4036. }
  4037. value.__smartArrayFlags[this._id] = this._duplicateId;
  4038. };
  4039. SmartArray.prototype.pushNoDuplicate = function (value) {
  4040. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4041. return;
  4042. }
  4043. this.push(value);
  4044. };
  4045. SmartArray.prototype.sort = function (compareFn) {
  4046. this.data.sort(compareFn);
  4047. };
  4048. SmartArray.prototype.reset = function () {
  4049. this.length = 0;
  4050. this._duplicateId++;
  4051. };
  4052. SmartArray.prototype.concat = function (array) {
  4053. if (array.length === 0) {
  4054. return;
  4055. }
  4056. if (this.length + array.length > this.data.length) {
  4057. this.data.length = (this.length + array.length) * 2;
  4058. }
  4059. for (var index = 0; index < array.length; index++) {
  4060. this.data[this.length++] = (array.data || array)[index];
  4061. }
  4062. };
  4063. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4064. if (array.length === 0) {
  4065. return;
  4066. }
  4067. if (this.length + array.length > this.data.length) {
  4068. this.data.length = (this.length + array.length) * 2;
  4069. }
  4070. for (var index = 0; index < array.length; index++) {
  4071. var item = (array.data || array)[index];
  4072. this.pushNoDuplicate(item);
  4073. }
  4074. };
  4075. SmartArray.prototype.indexOf = function (value) {
  4076. var position = this.data.indexOf(value);
  4077. if (position >= this.length) {
  4078. return -1;
  4079. }
  4080. return position;
  4081. };
  4082. // Statics
  4083. SmartArray._GlobalId = 0;
  4084. return SmartArray;
  4085. })();
  4086. BABYLON.SmartArray = SmartArray;
  4087. })(BABYLON || (BABYLON = {}));
  4088. var BABYLON;
  4089. (function (BABYLON) {
  4090. /**
  4091. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4092. * The underlying implemetation relies on an associative array to ensure the best performances.
  4093. * The value can be anything including 'null' but except 'undefined'
  4094. */
  4095. var StringDictionary = (function () {
  4096. function StringDictionary() {
  4097. this._count = 0;
  4098. this._data = {};
  4099. }
  4100. /**
  4101. * Get a value based from its key
  4102. * @param key the given key to get the matching value from
  4103. * @return the value if found, otherwise undefined is returned
  4104. */
  4105. StringDictionary.prototype.get = function (key) {
  4106. var val = this._data[key];
  4107. if (val !== undefined) {
  4108. return val;
  4109. }
  4110. return undefined;
  4111. };
  4112. /**
  4113. * Get a value from its key or add it if it doesn't exist.
  4114. * This method will ensure you that a given key/data will be present in the dictionary.
  4115. * @param key the given key to get the matchin value from
  4116. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4117. * The factory will only be invoked if there's no data for the given key.
  4118. * @return the value corresponding to the key.
  4119. */
  4120. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4121. var val = this.get(key);
  4122. if (val !== undefined) {
  4123. return val;
  4124. }
  4125. val = factory(key);
  4126. if (val) {
  4127. this.add(key, val);
  4128. }
  4129. return val;
  4130. };
  4131. /**
  4132. * Get a value from its key if present in the dictionary otherwise add it
  4133. * @param key the key to get the value from
  4134. * @param val if there's no such key/value pair in the dictionary add it with this value
  4135. * @return the value corresponding to the key
  4136. */
  4137. StringDictionary.prototype.getOrAdd = function (key, val) {
  4138. var val = this.get(key);
  4139. if (val !== undefined) {
  4140. return val;
  4141. }
  4142. this.add(key, val);
  4143. return val;
  4144. };
  4145. /**
  4146. * Check if there's a given key in the dictionary
  4147. * @param key the key to check for
  4148. * @return true if the key is present, false otherwise
  4149. */
  4150. StringDictionary.prototype.contains = function (key) {
  4151. return this._data[key] !== undefined;
  4152. };
  4153. /**
  4154. * Add a new key and its corresponding value
  4155. * @param key the key to add
  4156. * @param value the value corresponding to the key
  4157. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4158. */
  4159. StringDictionary.prototype.add = function (key, value) {
  4160. if (this._data[key] !== undefined) {
  4161. return false;
  4162. }
  4163. this._data[key] = value;
  4164. ++this._count;
  4165. return true;
  4166. };
  4167. /**
  4168. * Remove a key/value from the dictionary.
  4169. * @param key the key to remove
  4170. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4171. */
  4172. StringDictionary.prototype.remove = function (key) {
  4173. if (this.contains(key)) {
  4174. delete this._data[key];
  4175. --this._count;
  4176. return true;
  4177. }
  4178. return false;
  4179. };
  4180. /**
  4181. * Clear the whole content of the dictionary
  4182. */
  4183. StringDictionary.prototype.clear = function () {
  4184. this._data = {};
  4185. this._count = 0;
  4186. };
  4187. Object.defineProperty(StringDictionary.prototype, "count", {
  4188. get: function () {
  4189. return this._count;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. /**
  4195. * Execute a callback on each key/val of the dictionary.
  4196. * Note that you can remove any element in this dictionary in the callback implementation
  4197. * @param callback the callback to execute on a given key/value pair
  4198. */
  4199. StringDictionary.prototype.forEach = function (callback) {
  4200. for (var cur in this._data) {
  4201. var val = this._data[cur];
  4202. callback(cur, val);
  4203. }
  4204. };
  4205. /**
  4206. * Execute a callback on every occurence of the dictionary until it returns a valid TRes object.
  4207. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4208. * Note that you can remove any element in this dictionary in the callback implementation
  4209. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4210. */
  4211. StringDictionary.prototype.first = function (callback) {
  4212. for (var cur in this._data) {
  4213. var val = this._data[cur];
  4214. var res = callback(cur, val);
  4215. if (res) {
  4216. return res;
  4217. }
  4218. }
  4219. return null;
  4220. };
  4221. return StringDictionary;
  4222. })();
  4223. BABYLON.StringDictionary = StringDictionary;
  4224. })(BABYLON || (BABYLON = {}));
  4225. var BABYLON;
  4226. (function (BABYLON) {
  4227. // Screenshots
  4228. var screenshotCanvas;
  4229. var cloneValue = function (source, destinationObject) {
  4230. if (!source)
  4231. return null;
  4232. if (source instanceof BABYLON.Mesh) {
  4233. return null;
  4234. }
  4235. if (source instanceof BABYLON.SubMesh) {
  4236. return source.clone(destinationObject);
  4237. }
  4238. else if (source.clone) {
  4239. return source.clone();
  4240. }
  4241. return null;
  4242. };
  4243. var Tools = (function () {
  4244. function Tools() {
  4245. }
  4246. Tools.Instantiate = function (className) {
  4247. var arr = className.split(".");
  4248. var fn = (window || this);
  4249. for (var i = 0, len = arr.length; i < len; i++) {
  4250. fn = fn[arr[i]];
  4251. }
  4252. if (typeof fn !== "function") {
  4253. return null;
  4254. }
  4255. return fn;
  4256. };
  4257. Tools.SetImmediate = function (action) {
  4258. if (window.setImmediate) {
  4259. window.setImmediate(action);
  4260. }
  4261. else {
  4262. setTimeout(action, 1);
  4263. }
  4264. };
  4265. Tools.IsExponentOfTwo = function (value) {
  4266. var count = 1;
  4267. do {
  4268. count *= 2;
  4269. } while (count < value);
  4270. return count === value;
  4271. };
  4272. Tools.GetExponentOfTwo = function (value, max) {
  4273. var count = 1;
  4274. do {
  4275. count *= 2;
  4276. } while (count < value);
  4277. if (count > max)
  4278. count = max;
  4279. return count;
  4280. };
  4281. Tools.GetFilename = function (path) {
  4282. var index = path.lastIndexOf("/");
  4283. if (index < 0)
  4284. return path;
  4285. return path.substring(index + 1);
  4286. };
  4287. Tools.GetDOMTextContent = function (element) {
  4288. var result = "";
  4289. var child = element.firstChild;
  4290. while (child) {
  4291. if (child.nodeType === 3) {
  4292. result += child.textContent;
  4293. }
  4294. child = child.nextSibling;
  4295. }
  4296. return result;
  4297. };
  4298. Tools.ToDegrees = function (angle) {
  4299. return angle * 180 / Math.PI;
  4300. };
  4301. Tools.ToRadians = function (angle) {
  4302. return angle * Math.PI / 180;
  4303. };
  4304. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4305. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4306. var output = "";
  4307. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4308. var i = 0;
  4309. var bytes = new Uint8Array(buffer);
  4310. while (i < bytes.length) {
  4311. chr1 = bytes[i++];
  4312. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4313. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4314. enc1 = chr1 >> 2;
  4315. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4316. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4317. enc4 = chr3 & 63;
  4318. if (isNaN(chr2)) {
  4319. enc3 = enc4 = 64;
  4320. }
  4321. else if (isNaN(chr3)) {
  4322. enc4 = 64;
  4323. }
  4324. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4325. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4326. }
  4327. return "data:image/png;base64," + output;
  4328. };
  4329. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4330. if (bias === void 0) { bias = null; }
  4331. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4332. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4333. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4334. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4335. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4336. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4337. }
  4338. if (bias) {
  4339. minimum.x -= minimum.x * bias.x + bias.y;
  4340. minimum.y -= minimum.y * bias.x + bias.y;
  4341. minimum.z -= minimum.z * bias.x + bias.y;
  4342. maximum.x += maximum.x * bias.x + bias.y;
  4343. maximum.y += maximum.y * bias.x + bias.y;
  4344. maximum.z += maximum.z * bias.x + bias.y;
  4345. }
  4346. return {
  4347. minimum: minimum,
  4348. maximum: maximum
  4349. };
  4350. };
  4351. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4352. if (bias === void 0) { bias = null; }
  4353. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4354. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4355. for (var index = start; index < start + count; index++) {
  4356. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4357. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4358. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4359. }
  4360. if (bias) {
  4361. minimum.x -= minimum.x * bias.x + bias.y;
  4362. minimum.y -= minimum.y * bias.x + bias.y;
  4363. minimum.z -= minimum.z * bias.x + bias.y;
  4364. maximum.x += maximum.x * bias.x + bias.y;
  4365. maximum.y += maximum.y * bias.x + bias.y;
  4366. maximum.z += maximum.z * bias.x + bias.y;
  4367. }
  4368. return {
  4369. minimum: minimum,
  4370. maximum: maximum
  4371. };
  4372. };
  4373. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4374. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4375. return undefined;
  4376. return Array.isArray(obj) ? obj : [obj];
  4377. };
  4378. // Misc.
  4379. Tools.GetPointerPrefix = function () {
  4380. var eventPrefix = "pointer";
  4381. // Check if pointer events are supported
  4382. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4383. eventPrefix = "mouse";
  4384. }
  4385. return eventPrefix;
  4386. };
  4387. Tools.QueueNewFrame = function (func) {
  4388. if (window.requestAnimationFrame)
  4389. window.requestAnimationFrame(func);
  4390. else if (window.msRequestAnimationFrame)
  4391. window.msRequestAnimationFrame(func);
  4392. else if (window.webkitRequestAnimationFrame)
  4393. window.webkitRequestAnimationFrame(func);
  4394. else if (window.mozRequestAnimationFrame)
  4395. window.mozRequestAnimationFrame(func);
  4396. else if (window.oRequestAnimationFrame)
  4397. window.oRequestAnimationFrame(func);
  4398. else {
  4399. window.setTimeout(func, 16);
  4400. }
  4401. };
  4402. Tools.RequestFullscreen = function (element) {
  4403. if (element.requestFullscreen)
  4404. element.requestFullscreen();
  4405. else if (element.msRequestFullscreen)
  4406. element.msRequestFullscreen();
  4407. else if (element.webkitRequestFullscreen)
  4408. element.webkitRequestFullscreen();
  4409. else if (element.mozRequestFullScreen)
  4410. element.mozRequestFullScreen();
  4411. };
  4412. Tools.ExitFullscreen = function () {
  4413. if (document.exitFullscreen) {
  4414. document.exitFullscreen();
  4415. }
  4416. else if (document.mozCancelFullScreen) {
  4417. document.mozCancelFullScreen();
  4418. }
  4419. else if (document.webkitCancelFullScreen) {
  4420. document.webkitCancelFullScreen();
  4421. }
  4422. else if (document.msCancelFullScreen) {
  4423. document.msCancelFullScreen();
  4424. }
  4425. };
  4426. // External files
  4427. Tools.CleanUrl = function (url) {
  4428. url = url.replace(/#/mg, "%23");
  4429. return url;
  4430. };
  4431. Tools.LoadImage = function (url, onload, onerror, database) {
  4432. if (url instanceof ArrayBuffer) {
  4433. url = Tools.EncodeArrayBufferTobase64(url);
  4434. }
  4435. url = Tools.CleanUrl(url);
  4436. var img = new Image();
  4437. if (url.substr(0, 5) !== "data:") {
  4438. if (Tools.CorsBehavior) {
  4439. switch (typeof (Tools.CorsBehavior)) {
  4440. case "function":
  4441. var result = Tools.CorsBehavior(url);
  4442. if (result) {
  4443. img.crossOrigin = result;
  4444. }
  4445. break;
  4446. case "string":
  4447. default:
  4448. img.crossOrigin = Tools.CorsBehavior;
  4449. break;
  4450. }
  4451. }
  4452. }
  4453. img.onload = function () {
  4454. onload(img);
  4455. };
  4456. img.onerror = function (err) {
  4457. Tools.Error("Error while trying to load texture: " + url);
  4458. if (Tools.UseFallbackTexture) {
  4459. 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";
  4460. onload(img);
  4461. }
  4462. else {
  4463. onerror();
  4464. }
  4465. };
  4466. var noIndexedDB = function () {
  4467. img.src = url;
  4468. };
  4469. var loadFromIndexedDB = function () {
  4470. database.loadImageFromDB(url, img);
  4471. };
  4472. //ANY database to do!
  4473. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4474. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4475. }
  4476. else {
  4477. if (url.indexOf("file:") === -1) {
  4478. noIndexedDB();
  4479. }
  4480. else {
  4481. try {
  4482. var textureName = url.substring(5).toLowerCase();
  4483. var blobURL;
  4484. try {
  4485. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4486. }
  4487. catch (ex) {
  4488. // Chrome doesn't support oneTimeOnly parameter
  4489. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4490. }
  4491. img.src = blobURL;
  4492. }
  4493. catch (e) {
  4494. img.src = null;
  4495. }
  4496. }
  4497. }
  4498. return img;
  4499. };
  4500. //ANY
  4501. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4502. url = Tools.CleanUrl(url);
  4503. var noIndexedDB = function () {
  4504. var request = new XMLHttpRequest();
  4505. var loadUrl = Tools.BaseUrl + url;
  4506. request.open('GET', loadUrl, true);
  4507. if (useArrayBuffer) {
  4508. request.responseType = "arraybuffer";
  4509. }
  4510. request.onprogress = progressCallBack;
  4511. request.onreadystatechange = function () {
  4512. if (request.readyState === 4) {
  4513. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4514. callback(!useArrayBuffer ? request.responseText : request.response);
  4515. }
  4516. else {
  4517. if (onError) {
  4518. onError();
  4519. }
  4520. else {
  4521. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4522. }
  4523. }
  4524. }
  4525. };
  4526. request.send(null);
  4527. };
  4528. var loadFromIndexedDB = function () {
  4529. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4530. };
  4531. if (url.indexOf("file:") !== -1) {
  4532. var fileName = url.substring(5).toLowerCase();
  4533. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4534. }
  4535. else {
  4536. // Caching all files
  4537. if (database && database.enableSceneOffline) {
  4538. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4539. }
  4540. else {
  4541. noIndexedDB();
  4542. }
  4543. }
  4544. };
  4545. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4546. var reader = new FileReader();
  4547. reader.onload = function (e) {
  4548. //target doesn't have result from ts 1.3
  4549. callback(e.target['result']);
  4550. };
  4551. reader.onprogress = progressCallback;
  4552. reader.readAsDataURL(fileToLoad);
  4553. };
  4554. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4555. var reader = new FileReader();
  4556. reader.onerror = function (e) {
  4557. Tools.Log("Error while reading file: " + fileToLoad.name);
  4558. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4559. };
  4560. reader.onload = function (e) {
  4561. //target doesn't have result from ts 1.3
  4562. callback(e.target['result']);
  4563. };
  4564. reader.onprogress = progressCallBack;
  4565. if (!useArrayBuffer) {
  4566. // Asynchronous read
  4567. reader.readAsText(fileToLoad);
  4568. }
  4569. else {
  4570. reader.readAsArrayBuffer(fileToLoad);
  4571. }
  4572. };
  4573. //returns a downloadable url to a file content.
  4574. Tools.FileAsURL = function (content) {
  4575. var fileBlob = new Blob([content]);
  4576. var url = window.URL || window.webkitURL;
  4577. var link = url.createObjectURL(fileBlob);
  4578. return link;
  4579. };
  4580. // Misc.
  4581. Tools.Format = function (value, decimals) {
  4582. if (decimals === void 0) { decimals = 2; }
  4583. return value.toFixed(decimals);
  4584. };
  4585. Tools.CheckExtends = function (v, min, max) {
  4586. if (v.x < min.x)
  4587. min.x = v.x;
  4588. if (v.y < min.y)
  4589. min.y = v.y;
  4590. if (v.z < min.z)
  4591. min.z = v.z;
  4592. if (v.x > max.x)
  4593. max.x = v.x;
  4594. if (v.y > max.y)
  4595. max.y = v.y;
  4596. if (v.z > max.z)
  4597. max.z = v.z;
  4598. };
  4599. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4600. for (var prop in source) {
  4601. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4602. continue;
  4603. }
  4604. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4605. continue;
  4606. }
  4607. var sourceValue = source[prop];
  4608. var typeOfSourceValue = typeof sourceValue;
  4609. if (typeOfSourceValue === "function") {
  4610. continue;
  4611. }
  4612. if (typeOfSourceValue === "object") {
  4613. if (sourceValue instanceof Array) {
  4614. destination[prop] = [];
  4615. if (sourceValue.length > 0) {
  4616. if (typeof sourceValue[0] == "object") {
  4617. for (var index = 0; index < sourceValue.length; index++) {
  4618. var clonedValue = cloneValue(sourceValue[index], destination);
  4619. if (destination[prop].indexOf(clonedValue) === -1) {
  4620. destination[prop].push(clonedValue);
  4621. }
  4622. }
  4623. }
  4624. else {
  4625. destination[prop] = sourceValue.slice(0);
  4626. }
  4627. }
  4628. }
  4629. else {
  4630. destination[prop] = cloneValue(sourceValue, destination);
  4631. }
  4632. }
  4633. else {
  4634. destination[prop] = sourceValue;
  4635. }
  4636. }
  4637. };
  4638. Tools.IsEmpty = function (obj) {
  4639. for (var i in obj) {
  4640. return false;
  4641. }
  4642. return true;
  4643. };
  4644. Tools.RegisterTopRootEvents = function (events) {
  4645. for (var index = 0; index < events.length; index++) {
  4646. var event = events[index];
  4647. window.addEventListener(event.name, event.handler, false);
  4648. try {
  4649. if (window.parent) {
  4650. window.parent.addEventListener(event.name, event.handler, false);
  4651. }
  4652. }
  4653. catch (e) {
  4654. }
  4655. }
  4656. };
  4657. Tools.UnregisterTopRootEvents = function (events) {
  4658. for (var index = 0; index < events.length; index++) {
  4659. var event = events[index];
  4660. window.removeEventListener(event.name, event.handler);
  4661. try {
  4662. if (window.parent) {
  4663. window.parent.removeEventListener(event.name, event.handler);
  4664. }
  4665. }
  4666. catch (e) {
  4667. }
  4668. }
  4669. };
  4670. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4671. // Read the contents of the framebuffer
  4672. var numberOfChannelsByLine = width * 4;
  4673. var halfHeight = height / 2;
  4674. //Reading datas from WebGL
  4675. var data = engine.readPixels(0, 0, width, height);
  4676. //To flip image on Y axis.
  4677. for (var i = 0; i < halfHeight; i++) {
  4678. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4679. var currentCell = j + i * numberOfChannelsByLine;
  4680. var targetLine = height - i - 1;
  4681. var targetCell = j + targetLine * numberOfChannelsByLine;
  4682. var temp = data[currentCell];
  4683. data[currentCell] = data[targetCell];
  4684. data[targetCell] = temp;
  4685. }
  4686. }
  4687. // Create a 2D canvas to store the result
  4688. if (!screenshotCanvas) {
  4689. screenshotCanvas = document.createElement('canvas');
  4690. }
  4691. screenshotCanvas.width = width;
  4692. screenshotCanvas.height = height;
  4693. var context = screenshotCanvas.getContext('2d');
  4694. // Copy the pixels to a 2D canvas
  4695. var imageData = context.createImageData(width, height);
  4696. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4697. var castData = imageData.data;
  4698. castData.set(data);
  4699. context.putImageData(imageData, 0, 0);
  4700. var base64Image = screenshotCanvas.toDataURL();
  4701. if (successCallback) {
  4702. successCallback(base64Image);
  4703. }
  4704. else {
  4705. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4706. if (("download" in document.createElement("a"))) {
  4707. var a = window.document.createElement("a");
  4708. a.href = base64Image;
  4709. var date = new Date();
  4710. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4711. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4712. window.document.body.appendChild(a);
  4713. a.addEventListener("click", function () {
  4714. a.parentElement.removeChild(a);
  4715. });
  4716. a.click();
  4717. }
  4718. else {
  4719. var newWindow = window.open("");
  4720. var img = newWindow.document.createElement("img");
  4721. img.src = base64Image;
  4722. newWindow.document.body.appendChild(img);
  4723. }
  4724. }
  4725. };
  4726. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4727. var width;
  4728. var height;
  4729. //If a precision value is specified
  4730. if (size.precision) {
  4731. width = Math.round(engine.getRenderWidth() * size.precision);
  4732. height = Math.round(width / engine.getAspectRatio(camera));
  4733. size = { width: width, height: height };
  4734. }
  4735. else if (size.width && size.height) {
  4736. width = size.width;
  4737. height = size.height;
  4738. }
  4739. else if (size.width && !size.height) {
  4740. width = size.width;
  4741. height = Math.round(width / engine.getAspectRatio(camera));
  4742. size = { width: width, height: height };
  4743. }
  4744. else if (size.height && !size.width) {
  4745. height = size.height;
  4746. width = Math.round(height * engine.getAspectRatio(camera));
  4747. size = { width: width, height: height };
  4748. }
  4749. else if (!isNaN(size)) {
  4750. height = size;
  4751. width = size;
  4752. }
  4753. else {
  4754. Tools.Error("Invalid 'size' parameter !");
  4755. return;
  4756. }
  4757. var scene = camera.getScene();
  4758. var previousCamera = null;
  4759. if (scene.activeCamera !== camera) {
  4760. previousCamera = scene.activeCamera;
  4761. scene.activeCamera = camera;
  4762. }
  4763. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4764. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4765. texture.renderList = scene.meshes;
  4766. texture.onAfterRender = function () {
  4767. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4768. };
  4769. scene.incrementRenderId();
  4770. texture.render(true);
  4771. texture.dispose();
  4772. if (previousCamera) {
  4773. scene.activeCamera = previousCamera;
  4774. }
  4775. camera.getProjectionMatrix(true); // Force cache refresh;
  4776. };
  4777. // XHR response validator for local file scenario
  4778. Tools.ValidateXHRData = function (xhr, dataType) {
  4779. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4780. if (dataType === void 0) { dataType = 7; }
  4781. try {
  4782. if (dataType & 1) {
  4783. if (xhr.responseText && xhr.responseText.length > 0) {
  4784. return true;
  4785. }
  4786. else if (dataType === 1) {
  4787. return false;
  4788. }
  4789. }
  4790. if (dataType & 2) {
  4791. // Check header width and height since there is no "TGA" magic number
  4792. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4793. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4794. return true;
  4795. }
  4796. else if (dataType === 2) {
  4797. return false;
  4798. }
  4799. }
  4800. if (dataType & 4) {
  4801. // Check for the "DDS" magic number
  4802. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4803. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4804. return true;
  4805. }
  4806. else {
  4807. return false;
  4808. }
  4809. }
  4810. }
  4811. catch (e) {
  4812. }
  4813. return false;
  4814. };
  4815. Tools.getClassName = function (obj) {
  4816. var funcNameRegex = /function (.{1,})\(/;
  4817. var results = (funcNameRegex).exec((obj).constructor.toString());
  4818. return (results && results.length > 1) ? results[1] : "";
  4819. };
  4820. Object.defineProperty(Tools, "NoneLogLevel", {
  4821. get: function () {
  4822. return Tools._NoneLogLevel;
  4823. },
  4824. enumerable: true,
  4825. configurable: true
  4826. });
  4827. Object.defineProperty(Tools, "MessageLogLevel", {
  4828. get: function () {
  4829. return Tools._MessageLogLevel;
  4830. },
  4831. enumerable: true,
  4832. configurable: true
  4833. });
  4834. Object.defineProperty(Tools, "WarningLogLevel", {
  4835. get: function () {
  4836. return Tools._WarningLogLevel;
  4837. },
  4838. enumerable: true,
  4839. configurable: true
  4840. });
  4841. Object.defineProperty(Tools, "ErrorLogLevel", {
  4842. get: function () {
  4843. return Tools._ErrorLogLevel;
  4844. },
  4845. enumerable: true,
  4846. configurable: true
  4847. });
  4848. Object.defineProperty(Tools, "AllLogLevel", {
  4849. get: function () {
  4850. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4851. },
  4852. enumerable: true,
  4853. configurable: true
  4854. });
  4855. Tools._AddLogEntry = function (entry) {
  4856. Tools._LogCache = entry + Tools._LogCache;
  4857. if (Tools.OnNewCacheEntry) {
  4858. Tools.OnNewCacheEntry(entry);
  4859. }
  4860. };
  4861. Tools._FormatMessage = function (message) {
  4862. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4863. var date = new Date();
  4864. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4865. };
  4866. Tools._LogDisabled = function (message) {
  4867. // nothing to do
  4868. };
  4869. Tools._LogEnabled = function (message) {
  4870. var formattedMessage = Tools._FormatMessage(message);
  4871. console.log("BJS - " + formattedMessage);
  4872. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4873. Tools._AddLogEntry(entry);
  4874. };
  4875. Tools._WarnDisabled = function (message) {
  4876. // nothing to do
  4877. };
  4878. Tools._WarnEnabled = function (message) {
  4879. var formattedMessage = Tools._FormatMessage(message);
  4880. console.warn("BJS - " + formattedMessage);
  4881. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4882. Tools._AddLogEntry(entry);
  4883. };
  4884. Tools._ErrorDisabled = function (message) {
  4885. // nothing to do
  4886. };
  4887. Tools._ErrorEnabled = function (message) {
  4888. Tools.errorsCount++;
  4889. var formattedMessage = Tools._FormatMessage(message);
  4890. console.error("BJS - " + formattedMessage);
  4891. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4892. Tools._AddLogEntry(entry);
  4893. };
  4894. Object.defineProperty(Tools, "LogCache", {
  4895. get: function () {
  4896. return Tools._LogCache;
  4897. },
  4898. enumerable: true,
  4899. configurable: true
  4900. });
  4901. Tools.ClearLogCache = function () {
  4902. Tools._LogCache = "";
  4903. Tools.errorsCount = 0;
  4904. };
  4905. Object.defineProperty(Tools, "LogLevels", {
  4906. set: function (level) {
  4907. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4908. Tools.Log = Tools._LogEnabled;
  4909. }
  4910. else {
  4911. Tools.Log = Tools._LogDisabled;
  4912. }
  4913. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4914. Tools.Warn = Tools._WarnEnabled;
  4915. }
  4916. else {
  4917. Tools.Warn = Tools._WarnDisabled;
  4918. }
  4919. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4920. Tools.Error = Tools._ErrorEnabled;
  4921. }
  4922. else {
  4923. Tools.Error = Tools._ErrorDisabled;
  4924. }
  4925. },
  4926. enumerable: true,
  4927. configurable: true
  4928. });
  4929. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4930. get: function () {
  4931. return Tools._PerformanceNoneLogLevel;
  4932. },
  4933. enumerable: true,
  4934. configurable: true
  4935. });
  4936. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4937. get: function () {
  4938. return Tools._PerformanceUserMarkLogLevel;
  4939. },
  4940. enumerable: true,
  4941. configurable: true
  4942. });
  4943. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4944. get: function () {
  4945. return Tools._PerformanceConsoleLogLevel;
  4946. },
  4947. enumerable: true,
  4948. configurable: true
  4949. });
  4950. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4951. set: function (level) {
  4952. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4953. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4954. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4955. return;
  4956. }
  4957. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4958. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4959. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4960. return;
  4961. }
  4962. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4963. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4964. },
  4965. enumerable: true,
  4966. configurable: true
  4967. });
  4968. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4969. };
  4970. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4971. };
  4972. Tools._StartUserMark = function (counterName, condition) {
  4973. if (condition === void 0) { condition = true; }
  4974. if (!condition || !Tools._performance.mark) {
  4975. return;
  4976. }
  4977. Tools._performance.mark(counterName + "-Begin");
  4978. };
  4979. Tools._EndUserMark = function (counterName, condition) {
  4980. if (condition === void 0) { condition = true; }
  4981. if (!condition || !Tools._performance.mark) {
  4982. return;
  4983. }
  4984. Tools._performance.mark(counterName + "-End");
  4985. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4986. };
  4987. Tools._StartPerformanceConsole = function (counterName, condition) {
  4988. if (condition === void 0) { condition = true; }
  4989. if (!condition) {
  4990. return;
  4991. }
  4992. Tools._StartUserMark(counterName, condition);
  4993. if (console.time) {
  4994. console.time(counterName);
  4995. }
  4996. };
  4997. Tools._EndPerformanceConsole = function (counterName, condition) {
  4998. if (condition === void 0) { condition = true; }
  4999. if (!condition) {
  5000. return;
  5001. }
  5002. Tools._EndUserMark(counterName, condition);
  5003. if (console.time) {
  5004. console.timeEnd(counterName);
  5005. }
  5006. };
  5007. Object.defineProperty(Tools, "Now", {
  5008. get: function () {
  5009. if (window.performance && window.performance.now) {
  5010. return window.performance.now();
  5011. }
  5012. return new Date().getTime();
  5013. },
  5014. enumerable: true,
  5015. configurable: true
  5016. });
  5017. Tools.BaseUrl = "";
  5018. Tools.CorsBehavior = "anonymous";
  5019. Tools.UseFallbackTexture = true;
  5020. // Logs
  5021. Tools._NoneLogLevel = 0;
  5022. Tools._MessageLogLevel = 1;
  5023. Tools._WarningLogLevel = 2;
  5024. Tools._ErrorLogLevel = 4;
  5025. Tools._LogCache = "";
  5026. Tools.errorsCount = 0;
  5027. Tools.Log = Tools._LogEnabled;
  5028. Tools.Warn = Tools._WarnEnabled;
  5029. Tools.Error = Tools._ErrorEnabled;
  5030. // Performances
  5031. Tools._PerformanceNoneLogLevel = 0;
  5032. Tools._PerformanceUserMarkLogLevel = 1;
  5033. Tools._PerformanceConsoleLogLevel = 2;
  5034. Tools._performance = window.performance;
  5035. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5036. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5037. return Tools;
  5038. })();
  5039. BABYLON.Tools = Tools;
  5040. /**
  5041. * An implementation of a loop for asynchronous functions.
  5042. */
  5043. var AsyncLoop = (function () {
  5044. /**
  5045. * Constroctor.
  5046. * @param iterations the number of iterations.
  5047. * @param _fn the function to run each iteration
  5048. * @param _successCallback the callback that will be called upon succesful execution
  5049. * @param offset starting offset.
  5050. */
  5051. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5052. if (offset === void 0) { offset = 0; }
  5053. this.iterations = iterations;
  5054. this._fn = _fn;
  5055. this._successCallback = _successCallback;
  5056. this.index = offset - 1;
  5057. this._done = false;
  5058. }
  5059. /**
  5060. * Execute the next iteration. Must be called after the last iteration was finished.
  5061. */
  5062. AsyncLoop.prototype.executeNext = function () {
  5063. if (!this._done) {
  5064. if (this.index + 1 < this.iterations) {
  5065. ++this.index;
  5066. this._fn(this);
  5067. }
  5068. else {
  5069. this.breakLoop();
  5070. }
  5071. }
  5072. };
  5073. /**
  5074. * Break the loop and run the success callback.
  5075. */
  5076. AsyncLoop.prototype.breakLoop = function () {
  5077. this._done = true;
  5078. this._successCallback();
  5079. };
  5080. /**
  5081. * Helper function
  5082. */
  5083. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5084. if (offset === void 0) { offset = 0; }
  5085. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5086. loop.executeNext();
  5087. return loop;
  5088. };
  5089. /**
  5090. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5091. * @param iterations total number of iterations
  5092. * @param syncedIterations number of synchronous iterations in each async iteration.
  5093. * @param fn the function to call each iteration.
  5094. * @param callback a success call back that will be called when iterating stops.
  5095. * @param breakFunction a break condition (optional)
  5096. * @param timeout timeout settings for the setTimeout function. default - 0.
  5097. * @constructor
  5098. */
  5099. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5100. if (timeout === void 0) { timeout = 0; }
  5101. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5102. if (breakFunction && breakFunction())
  5103. loop.breakLoop();
  5104. else {
  5105. setTimeout(function () {
  5106. for (var i = 0; i < syncedIterations; ++i) {
  5107. var iteration = (loop.index * syncedIterations) + i;
  5108. if (iteration >= iterations)
  5109. break;
  5110. fn(iteration);
  5111. if (breakFunction && breakFunction()) {
  5112. loop.breakLoop();
  5113. break;
  5114. }
  5115. }
  5116. loop.executeNext();
  5117. }, timeout);
  5118. }
  5119. }, callback);
  5120. };
  5121. return AsyncLoop;
  5122. })();
  5123. BABYLON.AsyncLoop = AsyncLoop;
  5124. })(BABYLON || (BABYLON = {}));
  5125. var BABYLON;
  5126. (function (BABYLON) {
  5127. var Internals;
  5128. (function (Internals) {
  5129. var _AlphaState = (function () {
  5130. function _AlphaState() {
  5131. this._isAlphaBlendDirty = false;
  5132. this._isBlendFunctionParametersDirty = false;
  5133. this._alphaBlend = false;
  5134. this._blendFunctionParameters = new Array(4);
  5135. }
  5136. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5137. get: function () {
  5138. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5139. },
  5140. enumerable: true,
  5141. configurable: true
  5142. });
  5143. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5144. get: function () {
  5145. return this._alphaBlend;
  5146. },
  5147. set: function (value) {
  5148. if (this._alphaBlend === value) {
  5149. return;
  5150. }
  5151. this._alphaBlend = value;
  5152. this._isAlphaBlendDirty = true;
  5153. },
  5154. enumerable: true,
  5155. configurable: true
  5156. });
  5157. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5158. if (this._blendFunctionParameters[0] === value0 &&
  5159. this._blendFunctionParameters[1] === value1 &&
  5160. this._blendFunctionParameters[2] === value2 &&
  5161. this._blendFunctionParameters[3] === value3) {
  5162. return;
  5163. }
  5164. this._blendFunctionParameters[0] = value0;
  5165. this._blendFunctionParameters[1] = value1;
  5166. this._blendFunctionParameters[2] = value2;
  5167. this._blendFunctionParameters[3] = value3;
  5168. this._isBlendFunctionParametersDirty = true;
  5169. };
  5170. _AlphaState.prototype.reset = function () {
  5171. this._alphaBlend = false;
  5172. this._blendFunctionParameters[0] = null;
  5173. this._blendFunctionParameters[1] = null;
  5174. this._blendFunctionParameters[2] = null;
  5175. this._blendFunctionParameters[3] = null;
  5176. this._isAlphaBlendDirty = true;
  5177. this._isBlendFunctionParametersDirty = false;
  5178. };
  5179. _AlphaState.prototype.apply = function (gl) {
  5180. if (!this.isDirty) {
  5181. return;
  5182. }
  5183. // Alpha blend
  5184. if (this._isAlphaBlendDirty) {
  5185. if (this._alphaBlend) {
  5186. gl.enable(gl.BLEND);
  5187. }
  5188. else {
  5189. gl.disable(gl.BLEND);
  5190. }
  5191. this._isAlphaBlendDirty = false;
  5192. }
  5193. // Alpha function
  5194. if (this._isBlendFunctionParametersDirty) {
  5195. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5196. this._isBlendFunctionParametersDirty = false;
  5197. }
  5198. };
  5199. return _AlphaState;
  5200. })();
  5201. Internals._AlphaState = _AlphaState;
  5202. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5203. })(BABYLON || (BABYLON = {}));
  5204. var BABYLON;
  5205. (function (BABYLON) {
  5206. var Internals;
  5207. (function (Internals) {
  5208. var _DepthCullingState = (function () {
  5209. function _DepthCullingState() {
  5210. this._isDepthTestDirty = false;
  5211. this._isDepthMaskDirty = false;
  5212. this._isDepthFuncDirty = false;
  5213. this._isCullFaceDirty = false;
  5214. this._isCullDirty = false;
  5215. this._isZOffsetDirty = false;
  5216. }
  5217. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5218. get: function () {
  5219. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5220. },
  5221. enumerable: true,
  5222. configurable: true
  5223. });
  5224. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5225. get: function () {
  5226. return this._zOffset;
  5227. },
  5228. set: function (value) {
  5229. if (this._zOffset === value) {
  5230. return;
  5231. }
  5232. this._zOffset = value;
  5233. this._isZOffsetDirty = true;
  5234. },
  5235. enumerable: true,
  5236. configurable: true
  5237. });
  5238. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5239. get: function () {
  5240. return this._cullFace;
  5241. },
  5242. set: function (value) {
  5243. if (this._cullFace === value) {
  5244. return;
  5245. }
  5246. this._cullFace = value;
  5247. this._isCullFaceDirty = true;
  5248. },
  5249. enumerable: true,
  5250. configurable: true
  5251. });
  5252. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5253. get: function () {
  5254. return this._cull;
  5255. },
  5256. set: function (value) {
  5257. if (this._cull === value) {
  5258. return;
  5259. }
  5260. this._cull = value;
  5261. this._isCullDirty = true;
  5262. },
  5263. enumerable: true,
  5264. configurable: true
  5265. });
  5266. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5267. get: function () {
  5268. return this._depthFunc;
  5269. },
  5270. set: function (value) {
  5271. if (this._depthFunc === value) {
  5272. return;
  5273. }
  5274. this._depthFunc = value;
  5275. this._isDepthFuncDirty = true;
  5276. },
  5277. enumerable: true,
  5278. configurable: true
  5279. });
  5280. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5281. get: function () {
  5282. return this._depthMask;
  5283. },
  5284. set: function (value) {
  5285. if (this._depthMask === value) {
  5286. return;
  5287. }
  5288. this._depthMask = value;
  5289. this._isDepthMaskDirty = true;
  5290. },
  5291. enumerable: true,
  5292. configurable: true
  5293. });
  5294. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5295. get: function () {
  5296. return this._depthTest;
  5297. },
  5298. set: function (value) {
  5299. if (this._depthTest === value) {
  5300. return;
  5301. }
  5302. this._depthTest = value;
  5303. this._isDepthTestDirty = true;
  5304. },
  5305. enumerable: true,
  5306. configurable: true
  5307. });
  5308. _DepthCullingState.prototype.reset = function () {
  5309. this._depthMask = true;
  5310. this._depthTest = true;
  5311. this._depthFunc = null;
  5312. this._cull = null;
  5313. this._cullFace = null;
  5314. this._zOffset = 0;
  5315. this._isDepthTestDirty = true;
  5316. this._isDepthMaskDirty = true;
  5317. this._isDepthFuncDirty = false;
  5318. this._isCullFaceDirty = false;
  5319. this._isCullDirty = false;
  5320. this._isZOffsetDirty = false;
  5321. };
  5322. _DepthCullingState.prototype.apply = function (gl) {
  5323. if (!this.isDirty) {
  5324. return;
  5325. }
  5326. // Cull
  5327. if (this._isCullDirty) {
  5328. if (this.cull) {
  5329. gl.enable(gl.CULL_FACE);
  5330. }
  5331. else {
  5332. gl.disable(gl.CULL_FACE);
  5333. }
  5334. this._isCullDirty = false;
  5335. }
  5336. // Cull face
  5337. if (this._isCullFaceDirty) {
  5338. gl.cullFace(this.cullFace);
  5339. this._isCullFaceDirty = false;
  5340. }
  5341. // Depth mask
  5342. if (this._isDepthMaskDirty) {
  5343. gl.depthMask(this.depthMask);
  5344. this._isDepthMaskDirty = false;
  5345. }
  5346. // Depth test
  5347. if (this._isDepthTestDirty) {
  5348. if (this.depthTest) {
  5349. gl.enable(gl.DEPTH_TEST);
  5350. }
  5351. else {
  5352. gl.disable(gl.DEPTH_TEST);
  5353. }
  5354. this._isDepthTestDirty = false;
  5355. }
  5356. // Depth func
  5357. if (this._isDepthFuncDirty) {
  5358. gl.depthFunc(this.depthFunc);
  5359. this._isDepthFuncDirty = false;
  5360. }
  5361. // zOffset
  5362. if (this._isZOffsetDirty) {
  5363. if (this.zOffset) {
  5364. gl.enable(gl.POLYGON_OFFSET_FILL);
  5365. gl.polygonOffset(this.zOffset, 0);
  5366. }
  5367. else {
  5368. gl.disable(gl.POLYGON_OFFSET_FILL);
  5369. }
  5370. this._isZOffsetDirty = false;
  5371. }
  5372. };
  5373. return _DepthCullingState;
  5374. })();
  5375. Internals._DepthCullingState = _DepthCullingState;
  5376. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5377. })(BABYLON || (BABYLON = {}));
  5378. var BABYLON;
  5379. (function (BABYLON) {
  5380. var compileShader = function (gl, source, type, defines) {
  5381. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5382. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5383. gl.compileShader(shader);
  5384. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5385. throw new Error(gl.getShaderInfoLog(shader));
  5386. }
  5387. return shader;
  5388. };
  5389. var getWebGLTextureType = function (gl, type) {
  5390. var textureType = gl.UNSIGNED_BYTE;
  5391. if (type === Engine.TEXTURETYPE_FLOAT)
  5392. textureType = gl.FLOAT;
  5393. return textureType;
  5394. };
  5395. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5396. var magFilter = gl.NEAREST;
  5397. var minFilter = gl.NEAREST;
  5398. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5399. magFilter = gl.LINEAR;
  5400. if (generateMipMaps) {
  5401. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5402. }
  5403. else {
  5404. minFilter = gl.LINEAR;
  5405. }
  5406. }
  5407. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5408. magFilter = gl.LINEAR;
  5409. if (generateMipMaps) {
  5410. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5411. }
  5412. else {
  5413. minFilter = gl.LINEAR;
  5414. }
  5415. }
  5416. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5417. magFilter = gl.NEAREST;
  5418. if (generateMipMaps) {
  5419. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5420. }
  5421. else {
  5422. minFilter = gl.NEAREST;
  5423. }
  5424. }
  5425. return {
  5426. min: minFilter,
  5427. mag: magFilter
  5428. };
  5429. };
  5430. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5432. var engine = scene.getEngine();
  5433. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5434. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5435. gl.bindTexture(gl.TEXTURE_2D, texture);
  5436. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5437. texture._baseWidth = width;
  5438. texture._baseHeight = height;
  5439. texture._width = potWidth;
  5440. texture._height = potHeight;
  5441. texture.isReady = true;
  5442. processFunction(potWidth, potHeight);
  5443. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5444. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5446. if (!noMipmap && !isCompressed) {
  5447. gl.generateMipmap(gl.TEXTURE_2D);
  5448. }
  5449. gl.bindTexture(gl.TEXTURE_2D, null);
  5450. engine.resetTextureCache();
  5451. scene._removePendingData(texture);
  5452. if (onLoad) {
  5453. onLoad();
  5454. }
  5455. };
  5456. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5457. var img;
  5458. var onload = function () {
  5459. loadedImages[index] = img;
  5460. loadedImages._internalCount++;
  5461. scene._removePendingData(img);
  5462. if (loadedImages._internalCount === 6) {
  5463. onfinish(loadedImages);
  5464. }
  5465. };
  5466. var onerror = function () {
  5467. scene._removePendingData(img);
  5468. };
  5469. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5470. scene._addPendingData(img);
  5471. };
  5472. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5473. var loadedImages = [];
  5474. loadedImages._internalCount = 0;
  5475. for (var index = 0; index < 6; index++) {
  5476. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5477. }
  5478. };
  5479. var EngineCapabilities = (function () {
  5480. function EngineCapabilities() {
  5481. }
  5482. return EngineCapabilities;
  5483. })();
  5484. BABYLON.EngineCapabilities = EngineCapabilities;
  5485. /**
  5486. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5487. */
  5488. var Engine = (function () {
  5489. /**
  5490. * @constructor
  5491. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5492. * @param {boolean} [antialias] - enable antialias
  5493. * @param options - further options to be sent to the getContext function
  5494. */
  5495. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5496. var _this = this;
  5497. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5498. // Public members
  5499. this.isFullscreen = false;
  5500. this.isPointerLock = false;
  5501. this.cullBackFaces = true;
  5502. this.renderEvenInBackground = true;
  5503. // To enable/disable IDB support and avoid XHR on .manifest
  5504. this.enableOfflineSupport = true;
  5505. this.scenes = new Array();
  5506. this._windowIsBackground = false;
  5507. this._webGLVersion = "1.0";
  5508. this._drawCalls = 0;
  5509. this._renderingQueueLaunched = false;
  5510. this._activeRenderLoops = [];
  5511. // FPS
  5512. this.fpsRange = 60;
  5513. this.previousFramesDuration = [];
  5514. this.fps = 60;
  5515. this.deltaTime = 0;
  5516. // States
  5517. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5518. this._alphaState = new BABYLON.Internals._AlphaState();
  5519. this._alphaMode = Engine.ALPHA_DISABLE;
  5520. // Cache
  5521. this._loadedTexturesCache = new Array();
  5522. this._maxTextureChannels = 16;
  5523. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5524. this._compiledEffects = {};
  5525. this._uintIndicesCurrentlySet = false;
  5526. this._renderingCanvas = canvas;
  5527. options = options || {};
  5528. options.antialias = antialias;
  5529. if (options.preserveDrawingBuffer === undefined) {
  5530. options.preserveDrawingBuffer = false;
  5531. }
  5532. // GL
  5533. //try {
  5534. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5535. // if (this._gl) {
  5536. // this._webGLVersion = "2.0";
  5537. // }
  5538. //} catch (e) {
  5539. // // Do nothing
  5540. //}
  5541. if (!this._gl) {
  5542. try {
  5543. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5544. }
  5545. catch (e) {
  5546. throw new Error("WebGL not supported");
  5547. }
  5548. }
  5549. if (!this._gl) {
  5550. throw new Error("WebGL not supported");
  5551. }
  5552. this._onBlur = function () {
  5553. _this._windowIsBackground = true;
  5554. };
  5555. this._onFocus = function () {
  5556. _this._windowIsBackground = false;
  5557. };
  5558. window.addEventListener("blur", this._onBlur);
  5559. window.addEventListener("focus", this._onFocus);
  5560. // Viewport
  5561. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5562. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5563. this.resize();
  5564. // Caps
  5565. this._caps = new EngineCapabilities();
  5566. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5567. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5568. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5569. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5570. // Infos
  5571. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5572. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5573. if (rendererInfo != null) {
  5574. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5575. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5576. }
  5577. if (!this._glVendor) {
  5578. this._glVendor = "Unknown vendor";
  5579. }
  5580. if (!this._glRenderer) {
  5581. this._glRenderer = "Unknown renderer";
  5582. }
  5583. // Extensions
  5584. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5585. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5586. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5587. 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');
  5588. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5589. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5590. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5591. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5592. this._caps.highPrecisionShaderSupported = true;
  5593. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5594. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5595. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5596. if (this._gl.getShaderPrecisionFormat) {
  5597. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5598. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5599. }
  5600. // Depth buffer
  5601. this.setDepthBuffer(true);
  5602. this.setDepthFunctionToLessOrEqual();
  5603. this.setDepthWrite(true);
  5604. // Fullscreen
  5605. this._onFullscreenChange = function () {
  5606. if (document.fullscreen !== undefined) {
  5607. _this.isFullscreen = document.fullscreen;
  5608. }
  5609. else if (document.mozFullScreen !== undefined) {
  5610. _this.isFullscreen = document.mozFullScreen;
  5611. }
  5612. else if (document.webkitIsFullScreen !== undefined) {
  5613. _this.isFullscreen = document.webkitIsFullScreen;
  5614. }
  5615. else if (document.msIsFullScreen !== undefined) {
  5616. _this.isFullscreen = document.msIsFullScreen;
  5617. }
  5618. // Pointer lock
  5619. if (_this.isFullscreen && _this._pointerLockRequested) {
  5620. canvas.requestPointerLock = canvas.requestPointerLock ||
  5621. canvas.msRequestPointerLock ||
  5622. canvas.mozRequestPointerLock ||
  5623. canvas.webkitRequestPointerLock;
  5624. if (canvas.requestPointerLock) {
  5625. canvas.requestPointerLock();
  5626. }
  5627. }
  5628. };
  5629. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5630. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5631. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5632. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5633. // Pointer lock
  5634. this._onPointerLockChange = function () {
  5635. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5636. document.webkitPointerLockElement === canvas ||
  5637. document.msPointerLockElement === canvas ||
  5638. document.pointerLockElement === canvas);
  5639. };
  5640. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5641. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5642. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5643. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5644. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5645. Engine.audioEngine = new BABYLON.AudioEngine();
  5646. }
  5647. //default loading screen
  5648. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5649. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5650. }
  5651. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5652. get: function () {
  5653. return Engine._ALPHA_DISABLE;
  5654. },
  5655. enumerable: true,
  5656. configurable: true
  5657. });
  5658. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5659. get: function () {
  5660. return Engine._ALPHA_ONEONE;
  5661. },
  5662. enumerable: true,
  5663. configurable: true
  5664. });
  5665. Object.defineProperty(Engine, "ALPHA_ADD", {
  5666. get: function () {
  5667. return Engine._ALPHA_ADD;
  5668. },
  5669. enumerable: true,
  5670. configurable: true
  5671. });
  5672. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5673. get: function () {
  5674. return Engine._ALPHA_COMBINE;
  5675. },
  5676. enumerable: true,
  5677. configurable: true
  5678. });
  5679. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5680. get: function () {
  5681. return Engine._ALPHA_SUBTRACT;
  5682. },
  5683. enumerable: true,
  5684. configurable: true
  5685. });
  5686. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5687. get: function () {
  5688. return Engine._ALPHA_MULTIPLY;
  5689. },
  5690. enumerable: true,
  5691. configurable: true
  5692. });
  5693. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5694. get: function () {
  5695. return Engine._ALPHA_MAXIMIZED;
  5696. },
  5697. enumerable: true,
  5698. configurable: true
  5699. });
  5700. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5701. get: function () {
  5702. return Engine._DELAYLOADSTATE_NONE;
  5703. },
  5704. enumerable: true,
  5705. configurable: true
  5706. });
  5707. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5708. get: function () {
  5709. return Engine._DELAYLOADSTATE_LOADED;
  5710. },
  5711. enumerable: true,
  5712. configurable: true
  5713. });
  5714. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5715. get: function () {
  5716. return Engine._DELAYLOADSTATE_LOADING;
  5717. },
  5718. enumerable: true,
  5719. configurable: true
  5720. });
  5721. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5722. get: function () {
  5723. return Engine._DELAYLOADSTATE_NOTLOADED;
  5724. },
  5725. enumerable: true,
  5726. configurable: true
  5727. });
  5728. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5729. get: function () {
  5730. return Engine._TEXTUREFORMAT_ALPHA;
  5731. },
  5732. enumerable: true,
  5733. configurable: true
  5734. });
  5735. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5736. get: function () {
  5737. return Engine._TEXTUREFORMAT_LUMINANCE;
  5738. },
  5739. enumerable: true,
  5740. configurable: true
  5741. });
  5742. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5743. get: function () {
  5744. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5745. },
  5746. enumerable: true,
  5747. configurable: true
  5748. });
  5749. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5750. get: function () {
  5751. return Engine._TEXTUREFORMAT_RGB;
  5752. },
  5753. enumerable: true,
  5754. configurable: true
  5755. });
  5756. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5757. get: function () {
  5758. return Engine._TEXTUREFORMAT_RGBA;
  5759. },
  5760. enumerable: true,
  5761. configurable: true
  5762. });
  5763. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5764. get: function () {
  5765. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5766. },
  5767. enumerable: true,
  5768. configurable: true
  5769. });
  5770. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5771. get: function () {
  5772. return Engine._TEXTURETYPE_FLOAT;
  5773. },
  5774. enumerable: true,
  5775. configurable: true
  5776. });
  5777. Object.defineProperty(Engine, "Version", {
  5778. get: function () {
  5779. return "2.4.0-alpha";
  5780. },
  5781. enumerable: true,
  5782. configurable: true
  5783. });
  5784. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5785. get: function () {
  5786. return this._webGLVersion;
  5787. },
  5788. enumerable: true,
  5789. configurable: true
  5790. });
  5791. Engine.prototype._prepareWorkingCanvas = function () {
  5792. if (this._workingCanvas) {
  5793. return;
  5794. }
  5795. this._workingCanvas = document.createElement("canvas");
  5796. this._workingContext = this._workingCanvas.getContext("2d");
  5797. };
  5798. Engine.prototype.resetTextureCache = function () {
  5799. for (var index = 0; index < this._maxTextureChannels; index++) {
  5800. this._activeTexturesCache[index] = null;
  5801. }
  5802. };
  5803. Engine.prototype.getGlInfo = function () {
  5804. return {
  5805. vendor: this._glVendor,
  5806. renderer: this._glRenderer,
  5807. version: this._glVersion
  5808. };
  5809. };
  5810. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5811. if (useScreen === void 0) { useScreen = false; }
  5812. var viewport = camera.viewport;
  5813. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5814. };
  5815. Engine.prototype.getRenderWidth = function (useScreen) {
  5816. if (useScreen === void 0) { useScreen = false; }
  5817. if (!useScreen && this._currentRenderTarget) {
  5818. return this._currentRenderTarget._width;
  5819. }
  5820. return this._renderingCanvas.width;
  5821. };
  5822. Engine.prototype.getRenderHeight = function (useScreen) {
  5823. if (useScreen === void 0) { useScreen = false; }
  5824. if (!useScreen && this._currentRenderTarget) {
  5825. return this._currentRenderTarget._height;
  5826. }
  5827. return this._renderingCanvas.height;
  5828. };
  5829. Engine.prototype.getRenderingCanvas = function () {
  5830. return this._renderingCanvas;
  5831. };
  5832. Engine.prototype.getRenderingCanvasClientRect = function () {
  5833. return this._renderingCanvas.getBoundingClientRect();
  5834. };
  5835. Engine.prototype.setHardwareScalingLevel = function (level) {
  5836. this._hardwareScalingLevel = level;
  5837. this.resize();
  5838. };
  5839. Engine.prototype.getHardwareScalingLevel = function () {
  5840. return this._hardwareScalingLevel;
  5841. };
  5842. Engine.prototype.getLoadedTexturesCache = function () {
  5843. return this._loadedTexturesCache;
  5844. };
  5845. Engine.prototype.getCaps = function () {
  5846. return this._caps;
  5847. };
  5848. Object.defineProperty(Engine.prototype, "drawCalls", {
  5849. get: function () {
  5850. return this._drawCalls;
  5851. },
  5852. enumerable: true,
  5853. configurable: true
  5854. });
  5855. // Methods
  5856. Engine.prototype.resetDrawCalls = function () {
  5857. this._drawCalls = 0;
  5858. };
  5859. Engine.prototype.setDepthFunctionToGreater = function () {
  5860. this._depthCullingState.depthFunc = this._gl.GREATER;
  5861. };
  5862. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5863. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5864. };
  5865. Engine.prototype.setDepthFunctionToLess = function () {
  5866. this._depthCullingState.depthFunc = this._gl.LESS;
  5867. };
  5868. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5869. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5870. };
  5871. /**
  5872. * stop executing a render loop function and remove it from the execution array
  5873. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5874. */
  5875. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5876. if (!renderFunction) {
  5877. this._activeRenderLoops = [];
  5878. return;
  5879. }
  5880. var index = this._activeRenderLoops.indexOf(renderFunction);
  5881. if (index >= 0) {
  5882. this._activeRenderLoops.splice(index, 1);
  5883. }
  5884. };
  5885. Engine.prototype._renderLoop = function () {
  5886. var shouldRender = true;
  5887. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5888. shouldRender = false;
  5889. }
  5890. if (shouldRender) {
  5891. // Start new frame
  5892. this.beginFrame();
  5893. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5894. var renderFunction = this._activeRenderLoops[index];
  5895. renderFunction();
  5896. }
  5897. // Present
  5898. this.endFrame();
  5899. }
  5900. if (this._activeRenderLoops.length > 0) {
  5901. // Register new frame
  5902. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5903. }
  5904. else {
  5905. this._renderingQueueLaunched = false;
  5906. }
  5907. };
  5908. /**
  5909. * Register and execute a render loop. The engine can have more than one render function.
  5910. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5911. * @example
  5912. * engine.runRenderLoop(function () {
  5913. * scene.render()
  5914. * })
  5915. */
  5916. Engine.prototype.runRenderLoop = function (renderFunction) {
  5917. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5918. return;
  5919. }
  5920. this._activeRenderLoops.push(renderFunction);
  5921. if (!this._renderingQueueLaunched) {
  5922. this._renderingQueueLaunched = true;
  5923. this._bindedRenderFunction = this._renderLoop.bind(this);
  5924. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5925. }
  5926. };
  5927. /**
  5928. * Toggle full screen mode.
  5929. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5930. */
  5931. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5932. if (this.isFullscreen) {
  5933. BABYLON.Tools.ExitFullscreen();
  5934. }
  5935. else {
  5936. this._pointerLockRequested = requestPointerLock;
  5937. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5938. }
  5939. };
  5940. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5941. this.applyStates();
  5942. if (backBuffer) {
  5943. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5944. }
  5945. if (depthStencil && this._depthCullingState.depthMask) {
  5946. this._gl.clearDepth(1.0);
  5947. }
  5948. var mode = 0;
  5949. if (backBuffer) {
  5950. mode |= this._gl.COLOR_BUFFER_BIT;
  5951. }
  5952. if (depthStencil && this._depthCullingState.depthMask) {
  5953. mode |= this._gl.DEPTH_BUFFER_BIT;
  5954. }
  5955. this._gl.clear(mode);
  5956. };
  5957. /**
  5958. * Set the WebGL's viewport
  5959. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5960. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5961. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5962. */
  5963. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5964. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5965. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5966. var x = viewport.x || 0;
  5967. var y = viewport.y || 0;
  5968. this._cachedViewport = viewport;
  5969. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5970. };
  5971. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5972. this._cachedViewport = null;
  5973. this._gl.viewport(x, y, width, height);
  5974. };
  5975. Engine.prototype.beginFrame = function () {
  5976. this._measureFps();
  5977. };
  5978. Engine.prototype.endFrame = function () {
  5979. //this.flushFramebuffer();
  5980. };
  5981. /**
  5982. * resize the view according to the canvas' size.
  5983. * @example
  5984. * window.addEventListener("resize", function () {
  5985. * engine.resize();
  5986. * });
  5987. */
  5988. Engine.prototype.resize = function () {
  5989. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5990. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5991. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5992. for (var index = 0; index < this.scenes.length; index++) {
  5993. var scene = this.scenes[index];
  5994. if (scene.debugLayer.isVisible()) {
  5995. scene.debugLayer._syncPositions();
  5996. }
  5997. }
  5998. };
  5999. /**
  6000. * force a specific size of the canvas
  6001. * @param {number} width - the new canvas' width
  6002. * @param {number} height - the new canvas' height
  6003. */
  6004. Engine.prototype.setSize = function (width, height) {
  6005. this._renderingCanvas.width = width;
  6006. this._renderingCanvas.height = height;
  6007. for (var index = 0; index < this.scenes.length; index++) {
  6008. var scene = this.scenes[index];
  6009. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6010. var cam = scene.cameras[camIndex];
  6011. cam._currentRenderId = 0;
  6012. }
  6013. }
  6014. };
  6015. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6016. this._currentRenderTarget = texture;
  6017. var gl = this._gl;
  6018. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  6019. if (texture.isCube) {
  6020. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6021. }
  6022. else {
  6023. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6024. }
  6025. this._gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6026. this.wipeCaches();
  6027. };
  6028. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6029. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6030. this._currentRenderTarget = null;
  6031. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6032. var gl = this._gl;
  6033. gl.bindTexture(gl.TEXTURE_2D, texture);
  6034. gl.generateMipmap(gl.TEXTURE_2D);
  6035. gl.bindTexture(gl.TEXTURE_2D, null);
  6036. }
  6037. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6038. };
  6039. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6040. if (texture.generateMipMaps) {
  6041. var gl = this._gl;
  6042. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6043. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6044. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6045. }
  6046. };
  6047. Engine.prototype.flushFramebuffer = function () {
  6048. this._gl.flush();
  6049. };
  6050. Engine.prototype.restoreDefaultFramebuffer = function () {
  6051. this._currentRenderTarget = null;
  6052. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  6053. this.setViewport(this._cachedViewport);
  6054. this.wipeCaches();
  6055. };
  6056. // VBOs
  6057. Engine.prototype._resetVertexBufferBinding = function () {
  6058. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  6059. this._cachedVertexBuffers = null;
  6060. };
  6061. Engine.prototype.createVertexBuffer = function (vertices) {
  6062. var vbo = this._gl.createBuffer();
  6063. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6064. if (vertices instanceof Float32Array) {
  6065. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6066. }
  6067. else {
  6068. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6069. }
  6070. this._resetVertexBufferBinding();
  6071. vbo.references = 1;
  6072. return vbo;
  6073. };
  6074. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6075. var vbo = this._gl.createBuffer();
  6076. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6077. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6078. this._resetVertexBufferBinding();
  6079. vbo.references = 1;
  6080. return vbo;
  6081. };
  6082. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6083. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6084. if (offset === undefined) {
  6085. offset = 0;
  6086. }
  6087. if (vertices instanceof Float32Array) {
  6088. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6089. }
  6090. else {
  6091. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6092. }
  6093. this._resetVertexBufferBinding();
  6094. };
  6095. Engine.prototype._resetIndexBufferBinding = function () {
  6096. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6097. this._cachedIndexBuffer = null;
  6098. };
  6099. Engine.prototype.createIndexBuffer = function (indices) {
  6100. var vbo = this._gl.createBuffer();
  6101. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6102. // Check for 32 bits indices
  6103. var arrayBuffer;
  6104. var need32Bits = false;
  6105. if (this._caps.uintIndices) {
  6106. for (var index = 0; index < indices.length; index++) {
  6107. if (indices[index] > 65535) {
  6108. need32Bits = true;
  6109. break;
  6110. }
  6111. }
  6112. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6113. }
  6114. else {
  6115. arrayBuffer = new Uint16Array(indices);
  6116. }
  6117. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6118. this._resetIndexBufferBinding();
  6119. vbo.references = 1;
  6120. vbo.is32Bits = need32Bits;
  6121. return vbo;
  6122. };
  6123. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6124. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6125. this._cachedVertexBuffers = vertexBuffer;
  6126. this._cachedEffectForVertexBuffers = effect;
  6127. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6128. var offset = 0;
  6129. for (var index = 0; index < vertexDeclaration.length; index++) {
  6130. var order = effect.getAttributeLocation(index);
  6131. if (order >= 0) {
  6132. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6133. }
  6134. offset += vertexDeclaration[index] * 4;
  6135. }
  6136. }
  6137. if (this._cachedIndexBuffer !== indexBuffer) {
  6138. this._cachedIndexBuffer = indexBuffer;
  6139. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6140. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6141. }
  6142. };
  6143. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6144. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6145. this._cachedVertexBuffers = vertexBuffers;
  6146. this._cachedEffectForVertexBuffers = effect;
  6147. var attributes = effect.getAttributesNames();
  6148. for (var index = 0; index < attributes.length; index++) {
  6149. var order = effect.getAttributeLocation(index);
  6150. if (order >= 0) {
  6151. var vertexBuffer = vertexBuffers[attributes[index]];
  6152. if (!vertexBuffer) {
  6153. continue;
  6154. }
  6155. var stride = vertexBuffer.getStrideSize();
  6156. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6157. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6158. }
  6159. }
  6160. }
  6161. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6162. this._cachedIndexBuffer = indexBuffer;
  6163. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6164. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6165. }
  6166. };
  6167. Engine.prototype._releaseBuffer = function (buffer) {
  6168. buffer.references--;
  6169. if (buffer.references === 0) {
  6170. this._gl.deleteBuffer(buffer);
  6171. return true;
  6172. }
  6173. return false;
  6174. };
  6175. Engine.prototype.createInstancesBuffer = function (capacity) {
  6176. var buffer = this._gl.createBuffer();
  6177. buffer.capacity = capacity;
  6178. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6179. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6180. return buffer;
  6181. };
  6182. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6183. this._gl.deleteBuffer(buffer);
  6184. };
  6185. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6186. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6187. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6188. for (var index = 0; index < 4; index++) {
  6189. var offsetLocation = offsetLocations[index];
  6190. this._gl.enableVertexAttribArray(offsetLocation);
  6191. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6192. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6193. }
  6194. };
  6195. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6196. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6197. for (var index = 0; index < 4; index++) {
  6198. var offsetLocation = offsetLocations[index];
  6199. this._gl.disableVertexAttribArray(offsetLocation);
  6200. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6201. }
  6202. };
  6203. Engine.prototype.applyStates = function () {
  6204. this._depthCullingState.apply(this._gl);
  6205. this._alphaState.apply(this._gl);
  6206. };
  6207. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6208. // Apply states
  6209. this.applyStates();
  6210. this._drawCalls++;
  6211. // Render
  6212. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6213. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6214. if (instancesCount) {
  6215. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6216. return;
  6217. }
  6218. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6219. };
  6220. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6221. // Apply states
  6222. this.applyStates();
  6223. this._drawCalls++;
  6224. if (instancesCount) {
  6225. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6226. return;
  6227. }
  6228. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6229. };
  6230. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6231. // Apply states
  6232. this.applyStates();
  6233. this._drawCalls++;
  6234. if (instancesCount) {
  6235. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6236. return;
  6237. }
  6238. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6239. };
  6240. // Shaders
  6241. Engine.prototype._releaseEffect = function (effect) {
  6242. if (this._compiledEffects[effect._key]) {
  6243. delete this._compiledEffects[effect._key];
  6244. if (effect.getProgram()) {
  6245. this._gl.deleteProgram(effect.getProgram());
  6246. }
  6247. }
  6248. };
  6249. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  6250. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6251. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6252. var name = vertex + "+" + fragment + "@" + defines;
  6253. if (this._compiledEffects[name]) {
  6254. return this._compiledEffects[name];
  6255. }
  6256. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  6257. effect._key = name;
  6258. this._compiledEffects[name] = effect;
  6259. return effect;
  6260. };
  6261. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6262. if (uniformsNames === void 0) { uniformsNames = []; }
  6263. if (samplers === void 0) { samplers = []; }
  6264. if (defines === void 0) { defines = ""; }
  6265. return this.createEffect({
  6266. vertex: "particles",
  6267. fragmentElement: fragmentName
  6268. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6269. };
  6270. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6271. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6272. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6273. var shaderProgram = this._gl.createProgram();
  6274. this._gl.attachShader(shaderProgram, vertexShader);
  6275. this._gl.attachShader(shaderProgram, fragmentShader);
  6276. this._gl.linkProgram(shaderProgram);
  6277. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6278. if (!linked) {
  6279. var error = this._gl.getProgramInfoLog(shaderProgram);
  6280. if (error) {
  6281. throw new Error(error);
  6282. }
  6283. }
  6284. this._gl.deleteShader(vertexShader);
  6285. this._gl.deleteShader(fragmentShader);
  6286. return shaderProgram;
  6287. };
  6288. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6289. var results = [];
  6290. for (var index = 0; index < uniformsNames.length; index++) {
  6291. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6292. }
  6293. return results;
  6294. };
  6295. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6296. var results = [];
  6297. for (var index = 0; index < attributesNames.length; index++) {
  6298. try {
  6299. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6300. }
  6301. catch (e) {
  6302. results.push(-1);
  6303. }
  6304. }
  6305. return results;
  6306. };
  6307. Engine.prototype.enableEffect = function (effect) {
  6308. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6309. if (effect && effect.onBind) {
  6310. effect.onBind(effect);
  6311. }
  6312. return;
  6313. }
  6314. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6315. // Use program
  6316. this._gl.useProgram(effect.getProgram());
  6317. for (var i in this._vertexAttribArrays) {
  6318. //make sure this is a number)
  6319. var iAsNumber = +i;
  6320. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6321. continue;
  6322. }
  6323. this._vertexAttribArrays[iAsNumber] = false;
  6324. this._gl.disableVertexAttribArray(iAsNumber);
  6325. }
  6326. var attributesCount = effect.getAttributesCount();
  6327. for (var index = 0; index < attributesCount; index++) {
  6328. // Attributes
  6329. var order = effect.getAttributeLocation(index);
  6330. if (order >= 0) {
  6331. this._vertexAttribArrays[order] = true;
  6332. this._gl.enableVertexAttribArray(order);
  6333. }
  6334. }
  6335. this._currentEffect = effect;
  6336. if (effect.onBind) {
  6337. effect.onBind(effect);
  6338. }
  6339. };
  6340. Engine.prototype.setArray = function (uniform, array) {
  6341. if (!uniform)
  6342. return;
  6343. this._gl.uniform1fv(uniform, array);
  6344. };
  6345. Engine.prototype.setArray2 = function (uniform, array) {
  6346. if (!uniform || array.length % 2 !== 0)
  6347. return;
  6348. this._gl.uniform2fv(uniform, array);
  6349. };
  6350. Engine.prototype.setArray3 = function (uniform, array) {
  6351. if (!uniform || array.length % 3 !== 0)
  6352. return;
  6353. this._gl.uniform3fv(uniform, array);
  6354. };
  6355. Engine.prototype.setArray4 = function (uniform, array) {
  6356. if (!uniform || array.length % 4 !== 0)
  6357. return;
  6358. this._gl.uniform4fv(uniform, array);
  6359. };
  6360. Engine.prototype.setMatrices = function (uniform, matrices) {
  6361. if (!uniform)
  6362. return;
  6363. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6364. };
  6365. Engine.prototype.setMatrix = function (uniform, matrix) {
  6366. if (!uniform)
  6367. return;
  6368. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6369. };
  6370. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6371. if (!uniform)
  6372. return;
  6373. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6374. };
  6375. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6376. if (!uniform)
  6377. return;
  6378. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6379. };
  6380. Engine.prototype.setFloat = function (uniform, value) {
  6381. if (!uniform)
  6382. return;
  6383. this._gl.uniform1f(uniform, value);
  6384. };
  6385. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6386. if (!uniform)
  6387. return;
  6388. this._gl.uniform2f(uniform, x, y);
  6389. };
  6390. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6391. if (!uniform)
  6392. return;
  6393. this._gl.uniform3f(uniform, x, y, z);
  6394. };
  6395. Engine.prototype.setBool = function (uniform, bool) {
  6396. if (!uniform)
  6397. return;
  6398. this._gl.uniform1i(uniform, bool);
  6399. };
  6400. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6401. if (!uniform)
  6402. return;
  6403. this._gl.uniform4f(uniform, x, y, z, w);
  6404. };
  6405. Engine.prototype.setColor3 = function (uniform, color3) {
  6406. if (!uniform)
  6407. return;
  6408. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6409. };
  6410. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6411. if (!uniform)
  6412. return;
  6413. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6414. };
  6415. // States
  6416. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6417. if (zOffset === void 0) { zOffset = 0; }
  6418. if (reverseSide === void 0) { reverseSide = false; }
  6419. // Culling
  6420. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6421. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6422. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6423. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6424. if (culling) {
  6425. this._depthCullingState.cullFace = cullFace;
  6426. this._depthCullingState.cull = true;
  6427. }
  6428. else {
  6429. this._depthCullingState.cull = false;
  6430. }
  6431. }
  6432. // Z offset
  6433. this._depthCullingState.zOffset = zOffset;
  6434. };
  6435. Engine.prototype.setDepthBuffer = function (enable) {
  6436. this._depthCullingState.depthTest = enable;
  6437. };
  6438. Engine.prototype.getDepthWrite = function () {
  6439. return this._depthCullingState.depthMask;
  6440. };
  6441. Engine.prototype.setDepthWrite = function (enable) {
  6442. this._depthCullingState.depthMask = enable;
  6443. };
  6444. Engine.prototype.setColorWrite = function (enable) {
  6445. this._gl.colorMask(enable, enable, enable, enable);
  6446. };
  6447. Engine.prototype.setAlphaMode = function (mode) {
  6448. if (this._alphaMode === mode) {
  6449. return;
  6450. }
  6451. switch (mode) {
  6452. case Engine.ALPHA_DISABLE:
  6453. this.setDepthWrite(true);
  6454. this._alphaState.alphaBlend = false;
  6455. break;
  6456. case Engine.ALPHA_COMBINE:
  6457. this.setDepthWrite(false);
  6458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6459. this._alphaState.alphaBlend = true;
  6460. break;
  6461. case Engine.ALPHA_ONEONE:
  6462. this.setDepthWrite(false);
  6463. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6464. this._alphaState.alphaBlend = true;
  6465. break;
  6466. case Engine.ALPHA_ADD:
  6467. this.setDepthWrite(false);
  6468. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6469. this._alphaState.alphaBlend = true;
  6470. break;
  6471. case Engine.ALPHA_SUBTRACT:
  6472. this.setDepthWrite(false);
  6473. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6474. this._alphaState.alphaBlend = true;
  6475. break;
  6476. case Engine.ALPHA_MULTIPLY:
  6477. this.setDepthWrite(false);
  6478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6479. this._alphaState.alphaBlend = true;
  6480. break;
  6481. case Engine.ALPHA_MAXIMIZED:
  6482. this.setDepthWrite(false);
  6483. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6484. this._alphaState.alphaBlend = true;
  6485. break;
  6486. }
  6487. this._alphaMode = mode;
  6488. };
  6489. Engine.prototype.getAlphaMode = function () {
  6490. return this._alphaMode;
  6491. };
  6492. Engine.prototype.setAlphaTesting = function (enable) {
  6493. this._alphaTest = enable;
  6494. };
  6495. Engine.prototype.getAlphaTesting = function () {
  6496. return this._alphaTest;
  6497. };
  6498. // Textures
  6499. Engine.prototype.wipeCaches = function () {
  6500. this.resetTextureCache();
  6501. this._currentEffect = null;
  6502. this._depthCullingState.reset();
  6503. this._alphaState.reset();
  6504. this._cachedVertexBuffers = null;
  6505. this._cachedIndexBuffer = null;
  6506. this._cachedEffectForVertexBuffers = null;
  6507. };
  6508. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6509. var gl = this._gl;
  6510. gl.bindTexture(gl.TEXTURE_2D, texture);
  6511. var magFilter = gl.NEAREST;
  6512. var minFilter = gl.NEAREST;
  6513. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6514. magFilter = gl.LINEAR;
  6515. minFilter = gl.LINEAR;
  6516. }
  6517. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6518. magFilter = gl.LINEAR;
  6519. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6520. }
  6521. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6522. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6523. gl.bindTexture(gl.TEXTURE_2D, null);
  6524. texture.samplingMode = samplingMode;
  6525. };
  6526. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6527. var _this = this;
  6528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6529. if (onLoad === void 0) { onLoad = null; }
  6530. if (onError === void 0) { onError = null; }
  6531. if (buffer === void 0) { buffer = null; }
  6532. var texture = this._gl.createTexture();
  6533. var extension;
  6534. var fromData = false;
  6535. if (url.substr(0, 5) === "data:") {
  6536. fromData = true;
  6537. }
  6538. if (!fromData)
  6539. extension = url.substr(url.length - 4, 4).toLowerCase();
  6540. else {
  6541. var oldUrl = url;
  6542. fromData = oldUrl.split(':');
  6543. url = oldUrl;
  6544. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6545. }
  6546. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6547. var isTGA = (extension === ".tga");
  6548. scene._addPendingData(texture);
  6549. texture.url = url;
  6550. texture.noMipmap = noMipmap;
  6551. texture.references = 1;
  6552. texture.samplingMode = samplingMode;
  6553. this._loadedTexturesCache.push(texture);
  6554. var onerror = function () {
  6555. scene._removePendingData(texture);
  6556. if (onError) {
  6557. onError();
  6558. }
  6559. };
  6560. var callback;
  6561. if (isTGA) {
  6562. callback = function (arrayBuffer) {
  6563. var data = new Uint8Array(arrayBuffer);
  6564. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6565. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6566. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6567. }, onLoad, samplingMode);
  6568. };
  6569. if (!(fromData instanceof Array))
  6570. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6571. callback(arrayBuffer);
  6572. }, onerror, scene.database, true);
  6573. else
  6574. callback(buffer);
  6575. }
  6576. else if (isDDS) {
  6577. callback = function (data) {
  6578. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6579. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6580. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6581. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6582. }, onLoad, samplingMode);
  6583. };
  6584. if (!(fromData instanceof Array))
  6585. BABYLON.Tools.LoadFile(url, function (data) {
  6586. callback(data);
  6587. }, onerror, scene.database, true);
  6588. else
  6589. callback(buffer);
  6590. }
  6591. else {
  6592. var onload = function (img) {
  6593. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6594. var isPot = (img.width === potWidth && img.height === potHeight);
  6595. if (!isPot) {
  6596. _this._prepareWorkingCanvas();
  6597. _this._workingCanvas.width = potWidth;
  6598. _this._workingCanvas.height = potHeight;
  6599. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6600. _this._workingContext.imageSmoothingEnabled = false;
  6601. _this._workingContext.mozImageSmoothingEnabled = false;
  6602. _this._workingContext.oImageSmoothingEnabled = false;
  6603. _this._workingContext.webkitImageSmoothingEnabled = false;
  6604. _this._workingContext.msImageSmoothingEnabled = false;
  6605. }
  6606. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6607. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6608. _this._workingContext.imageSmoothingEnabled = true;
  6609. _this._workingContext.mozImageSmoothingEnabled = true;
  6610. _this._workingContext.oImageSmoothingEnabled = true;
  6611. _this._workingContext.webkitImageSmoothingEnabled = true;
  6612. _this._workingContext.msImageSmoothingEnabled = true;
  6613. }
  6614. }
  6615. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6616. }, onLoad, samplingMode);
  6617. };
  6618. if (!(fromData instanceof Array))
  6619. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6620. else
  6621. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6622. }
  6623. return texture;
  6624. };
  6625. Engine.prototype._getInternalFormat = function (format) {
  6626. var internalFormat = this._gl.RGBA;
  6627. switch (format) {
  6628. case Engine.TEXTUREFORMAT_ALPHA:
  6629. internalFormat = this._gl.ALPHA;
  6630. break;
  6631. case Engine.TEXTUREFORMAT_LUMINANCE:
  6632. internalFormat = this._gl.LUMINANCE;
  6633. break;
  6634. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6635. internalFormat = this._gl.LUMINANCE_ALPHA;
  6636. break;
  6637. case Engine.TEXTUREFORMAT_RGB:
  6638. internalFormat = this._gl.RGB;
  6639. break;
  6640. case Engine.TEXTUREFORMAT_RGBA:
  6641. internalFormat = this._gl.RGBA;
  6642. break;
  6643. }
  6644. return internalFormat;
  6645. };
  6646. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6647. if (compression === void 0) { compression = null; }
  6648. var internalFormat = this._getInternalFormat(format);
  6649. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6650. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6651. if (compression) {
  6652. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6653. }
  6654. else {
  6655. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6656. }
  6657. if (texture.generateMipMaps) {
  6658. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6659. }
  6660. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6661. this.resetTextureCache();
  6662. texture.isReady = true;
  6663. };
  6664. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6665. if (compression === void 0) { compression = null; }
  6666. var texture = this._gl.createTexture();
  6667. texture._baseWidth = width;
  6668. texture._baseHeight = height;
  6669. texture._width = width;
  6670. texture._height = height;
  6671. texture.references = 1;
  6672. this.updateRawTexture(texture, data, format, invertY, compression);
  6673. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6674. // Filters
  6675. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6676. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6677. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6678. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6679. texture.samplingMode = samplingMode;
  6680. this._loadedTexturesCache.push(texture);
  6681. return texture;
  6682. };
  6683. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6684. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6685. var texture = this._gl.createTexture();
  6686. texture._baseWidth = width;
  6687. texture._baseHeight = height;
  6688. if (forceExponantOfTwo) {
  6689. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6690. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6691. }
  6692. this.resetTextureCache();
  6693. texture._width = width;
  6694. texture._height = height;
  6695. texture.isReady = false;
  6696. texture.generateMipMaps = generateMipMaps;
  6697. texture.references = 1;
  6698. texture.samplingMode = samplingMode;
  6699. this.updateTextureSamplingMode(samplingMode, texture);
  6700. this._loadedTexturesCache.push(texture);
  6701. return texture;
  6702. };
  6703. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6704. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6705. if (texture.isCube) {
  6706. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6707. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6708. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6709. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6710. }
  6711. else {
  6712. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6713. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6714. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6715. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6716. }
  6717. };
  6718. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6719. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6720. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6721. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6722. if (texture.generateMipMaps) {
  6723. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6724. }
  6725. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6726. this.resetTextureCache();
  6727. texture.isReady = true;
  6728. };
  6729. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6730. if (texture._isDisabled) {
  6731. return;
  6732. }
  6733. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6734. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6735. try {
  6736. // Testing video texture support
  6737. if (this._videoTextureSupported === undefined) {
  6738. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6739. if (this._gl.getError() !== 0) {
  6740. this._videoTextureSupported = false;
  6741. }
  6742. else {
  6743. this._videoTextureSupported = true;
  6744. }
  6745. }
  6746. // Copy video through the current working canvas if video texture is not supported
  6747. if (!this._videoTextureSupported) {
  6748. if (!texture._workingCanvas) {
  6749. texture._workingCanvas = document.createElement("canvas");
  6750. texture._workingContext = texture._workingCanvas.getContext("2d");
  6751. texture._workingCanvas.width = texture._width;
  6752. texture._workingCanvas.height = texture._height;
  6753. }
  6754. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6755. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6756. }
  6757. else {
  6758. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6759. }
  6760. if (texture.generateMipMaps) {
  6761. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6762. }
  6763. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6764. this.resetTextureCache();
  6765. texture.isReady = true;
  6766. }
  6767. catch (ex) {
  6768. // Something unexpected
  6769. // Let's disable the texture
  6770. texture._isDisabled = true;
  6771. }
  6772. };
  6773. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6774. // old version had a "generateMipMaps" arg instead of options.
  6775. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6776. // in the same way, generateDepthBuffer is defaulted to true
  6777. var generateMipMaps = false;
  6778. var generateDepthBuffer = true;
  6779. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6780. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6781. if (options !== undefined) {
  6782. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6783. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6784. type = options.type === undefined ? type : options.type;
  6785. if (options.samplingMode !== undefined) {
  6786. samplingMode = options.samplingMode;
  6787. }
  6788. if (type === Engine.TEXTURETYPE_FLOAT) {
  6789. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6790. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6791. }
  6792. }
  6793. var gl = this._gl;
  6794. var texture = gl.createTexture();
  6795. gl.bindTexture(gl.TEXTURE_2D, texture);
  6796. var width = size.width || size;
  6797. var height = size.height || size;
  6798. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6799. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6800. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6801. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6802. }
  6803. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6805. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6806. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6807. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6808. var depthBuffer;
  6809. // Create the depth buffer
  6810. if (generateDepthBuffer) {
  6811. depthBuffer = gl.createRenderbuffer();
  6812. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6813. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6814. }
  6815. // Create the framebuffer
  6816. var framebuffer = gl.createFramebuffer();
  6817. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6818. if (generateDepthBuffer) {
  6819. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6820. }
  6821. if (generateMipMaps) {
  6822. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6823. }
  6824. // Unbind
  6825. gl.bindTexture(gl.TEXTURE_2D, null);
  6826. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6827. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6828. texture._framebuffer = framebuffer;
  6829. if (generateDepthBuffer) {
  6830. texture._depthBuffer = depthBuffer;
  6831. }
  6832. texture._width = width;
  6833. texture._height = height;
  6834. texture.isReady = true;
  6835. texture.generateMipMaps = generateMipMaps;
  6836. texture.references = 1;
  6837. texture.samplingMode = samplingMode;
  6838. this.resetTextureCache();
  6839. this._loadedTexturesCache.push(texture);
  6840. return texture;
  6841. };
  6842. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6843. var gl = this._gl;
  6844. var texture = gl.createTexture();
  6845. var generateMipMaps = true;
  6846. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6847. if (options !== undefined) {
  6848. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6849. if (options.samplingMode !== undefined) {
  6850. samplingMode = options.samplingMode;
  6851. }
  6852. }
  6853. texture.isCube = true;
  6854. texture.references = 1;
  6855. texture.generateMipMaps = generateMipMaps;
  6856. texture.references = 1;
  6857. texture.samplingMode = samplingMode;
  6858. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6859. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6860. for (var face = 0; face < 6; face++) {
  6861. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6862. }
  6863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6867. // Create the depth buffer
  6868. var depthBuffer = gl.createRenderbuffer();
  6869. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6870. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6871. // Create the framebuffer
  6872. var framebuffer = gl.createFramebuffer();
  6873. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6874. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6875. // Mipmaps
  6876. if (texture.generateMipMaps) {
  6877. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6878. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6879. }
  6880. // Unbind
  6881. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6882. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6883. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6884. texture._framebuffer = framebuffer;
  6885. texture._depthBuffer = depthBuffer;
  6886. this.resetTextureCache();
  6887. texture._width = size;
  6888. texture._height = size;
  6889. texture.isReady = true;
  6890. return texture;
  6891. };
  6892. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6893. var _this = this;
  6894. var gl = this._gl;
  6895. var texture = gl.createTexture();
  6896. texture.isCube = true;
  6897. texture.url = rootUrl;
  6898. texture.references = 1;
  6899. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6900. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6901. if (isDDS) {
  6902. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6903. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6904. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6905. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6906. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6907. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6908. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6909. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6910. }
  6911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6913. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6914. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6915. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6916. _this.resetTextureCache();
  6917. texture._width = info.width;
  6918. texture._height = info.height;
  6919. texture.isReady = true;
  6920. }, null, null, true);
  6921. }
  6922. else {
  6923. cascadeLoad(rootUrl, scene, function (imgs) {
  6924. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6925. var height = width;
  6926. _this._prepareWorkingCanvas();
  6927. _this._workingCanvas.width = width;
  6928. _this._workingCanvas.height = height;
  6929. var faces = [
  6930. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6931. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6932. ];
  6933. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6934. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6935. for (var index = 0; index < faces.length; index++) {
  6936. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6937. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6938. }
  6939. if (!noMipmap) {
  6940. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6941. }
  6942. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6943. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6944. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6945. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6946. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6947. _this.resetTextureCache();
  6948. texture._width = width;
  6949. texture._height = height;
  6950. texture.isReady = true;
  6951. }, files);
  6952. }
  6953. return texture;
  6954. };
  6955. Engine.prototype.updateTextureSize = function (texture, width, height) {
  6956. texture._width = width;
  6957. texture._height = height;
  6958. };
  6959. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6960. var _this = this;
  6961. var gl = this._gl;
  6962. var texture = gl.createTexture();
  6963. scene._addPendingData(texture);
  6964. texture.isCube = true;
  6965. texture.references = 1;
  6966. texture.url = url;
  6967. var internalFormat = this._getInternalFormat(format);
  6968. var textureType = gl.UNSIGNED_BYTE;
  6969. if (type === Engine.TEXTURETYPE_FLOAT) {
  6970. textureType = gl.FLOAT;
  6971. }
  6972. var width = size;
  6973. var height = width;
  6974. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6975. texture._width = width;
  6976. texture._height = height;
  6977. var onerror = function () {
  6978. scene._removePendingData(texture);
  6979. };
  6980. var internalCallback = function (data) {
  6981. var rgbeDataArrays = callback(data);
  6982. var facesIndex = [
  6983. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6984. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6985. ];
  6986. width = texture._width;
  6987. height = texture._height;
  6988. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6989. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6990. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6991. if (!noMipmap && isPot) {
  6992. if (mipmmapGenerator) {
  6993. var arrayTemp = [];
  6994. // Data are known to be in +X +Y +Z -X -Y -Z
  6995. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6996. arrayTemp.push(rgbeDataArrays[0]); // +X
  6997. arrayTemp.push(rgbeDataArrays[3]); // -X
  6998. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6999. arrayTemp.push(rgbeDataArrays[4]); // -Y
  7000. arrayTemp.push(rgbeDataArrays[2]); // +Z
  7001. arrayTemp.push(rgbeDataArrays[5]); // -Z
  7002. var mipData = mipmmapGenerator(arrayTemp);
  7003. for (var level = 0; level < mipData.length; level++) {
  7004. var mipSize = width >> level;
  7005. // mipData is order in +X -X +Y -Y +Z -Z
  7006. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  7007. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  7008. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  7009. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  7010. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  7011. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  7012. }
  7013. }
  7014. else {
  7015. // Data are known to be in +X +Y +Z -X -Y -Z
  7016. for (var index = 0; index < facesIndex.length; index++) {
  7017. var faceData = rgbeDataArrays[index];
  7018. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  7019. }
  7020. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7021. }
  7022. }
  7023. else {
  7024. noMipmap = true;
  7025. }
  7026. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  7027. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  7028. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  7029. }
  7030. else {
  7031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  7032. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  7033. }
  7034. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7035. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7036. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  7037. texture.isReady = true;
  7038. _this.resetTextureCache();
  7039. scene._removePendingData(texture);
  7040. };
  7041. BABYLON.Tools.LoadFile(url, function (data) {
  7042. internalCallback(data);
  7043. }, onerror, scene.database, true);
  7044. return texture;
  7045. };
  7046. ;
  7047. Engine.prototype._releaseTexture = function (texture) {
  7048. var gl = this._gl;
  7049. if (texture._framebuffer) {
  7050. gl.deleteFramebuffer(texture._framebuffer);
  7051. }
  7052. if (texture._depthBuffer) {
  7053. gl.deleteRenderbuffer(texture._depthBuffer);
  7054. }
  7055. gl.deleteTexture(texture);
  7056. // Unbind channels
  7057. this.unbindAllTextures();
  7058. var index = this._loadedTexturesCache.indexOf(texture);
  7059. if (index !== -1) {
  7060. this._loadedTexturesCache.splice(index, 1);
  7061. }
  7062. };
  7063. Engine.prototype.bindSamplers = function (effect) {
  7064. this._gl.useProgram(effect.getProgram());
  7065. var samplers = effect.getSamplers();
  7066. for (var index = 0; index < samplers.length; index++) {
  7067. var uniform = effect.getUniform(samplers[index]);
  7068. this._gl.uniform1i(uniform, index);
  7069. }
  7070. this._currentEffect = null;
  7071. };
  7072. Engine.prototype._bindTexture = function (channel, texture) {
  7073. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7074. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  7075. this._activeTexturesCache[channel] = null;
  7076. };
  7077. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7078. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7079. };
  7080. Engine.prototype.unbindAllTextures = function () {
  7081. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7082. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7083. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7084. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7085. this._activeTexturesCache[channel] = null;
  7086. }
  7087. };
  7088. Engine.prototype.setTexture = function (channel, texture) {
  7089. if (channel < 0) {
  7090. return;
  7091. }
  7092. // Not ready?
  7093. if (!texture || !texture.isReady()) {
  7094. if (this._activeTexturesCache[channel] != null) {
  7095. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7096. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7097. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7098. this._activeTexturesCache[channel] = null;
  7099. }
  7100. return;
  7101. }
  7102. // Video
  7103. var alreadyActivated = false;
  7104. if (texture instanceof BABYLON.VideoTexture) {
  7105. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7106. alreadyActivated = true;
  7107. texture.update();
  7108. }
  7109. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7110. texture.delayLoad();
  7111. return;
  7112. }
  7113. if (this._activeTexturesCache[channel] === texture) {
  7114. return;
  7115. }
  7116. this._activeTexturesCache[channel] = texture;
  7117. var internalTexture = texture.getInternalTexture();
  7118. if (!alreadyActivated) {
  7119. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7120. }
  7121. if (internalTexture.isCube) {
  7122. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7123. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7124. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7125. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7126. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7127. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7128. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7129. }
  7130. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7131. }
  7132. else {
  7133. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7134. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7135. internalTexture._cachedWrapU = texture.wrapU;
  7136. switch (texture.wrapU) {
  7137. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7138. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7139. break;
  7140. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7141. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7142. break;
  7143. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7144. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7145. break;
  7146. }
  7147. }
  7148. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7149. internalTexture._cachedWrapV = texture.wrapV;
  7150. switch (texture.wrapV) {
  7151. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7152. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7153. break;
  7154. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7155. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7156. break;
  7157. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7158. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7159. break;
  7160. }
  7161. }
  7162. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7163. }
  7164. };
  7165. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7166. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7167. var value = texture.anisotropicFilteringLevel;
  7168. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7169. value = 1;
  7170. }
  7171. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7172. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7173. texture._cachedAnisotropicFilteringLevel = value;
  7174. }
  7175. };
  7176. Engine.prototype.readPixels = function (x, y, width, height) {
  7177. var data = new Uint8Array(height * width * 4);
  7178. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7179. return data;
  7180. };
  7181. Engine.prototype.releaseInternalTexture = function (texture) {
  7182. if (!texture) {
  7183. return;
  7184. }
  7185. texture.references--;
  7186. // Final reference ?
  7187. if (texture.references === 0) {
  7188. var texturesCache = this.getLoadedTexturesCache();
  7189. var index = texturesCache.indexOf(texture);
  7190. if (index > -1) {
  7191. texturesCache.splice(index, 1);
  7192. }
  7193. this._releaseTexture(texture);
  7194. }
  7195. };
  7196. // Dispose
  7197. Engine.prototype.dispose = function () {
  7198. this.hideLoadingUI();
  7199. this.stopRenderLoop();
  7200. // Release scenes
  7201. while (this.scenes.length) {
  7202. this.scenes[0].dispose();
  7203. }
  7204. // Release audio engine
  7205. Engine.audioEngine.dispose();
  7206. // Release effects
  7207. for (var name in this._compiledEffects) {
  7208. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7209. }
  7210. // Unbind
  7211. for (var i in this._vertexAttribArrays) {
  7212. //making sure this is a string
  7213. var iAsNumber = +i;
  7214. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7215. continue;
  7216. }
  7217. this._gl.disableVertexAttribArray(iAsNumber);
  7218. }
  7219. this._gl = null;
  7220. // Events
  7221. window.removeEventListener("blur", this._onBlur);
  7222. window.removeEventListener("focus", this._onFocus);
  7223. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7224. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7225. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7226. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7227. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7228. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7229. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7230. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7231. };
  7232. // Loading screen
  7233. Engine.prototype.displayLoadingUI = function () {
  7234. this._loadingScreen.displayLoadingUI();
  7235. };
  7236. Engine.prototype.hideLoadingUI = function () {
  7237. this._loadingScreen.hideLoadingUI();
  7238. };
  7239. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7240. get: function () {
  7241. return this._loadingScreen;
  7242. },
  7243. set: function (loadingScreen) {
  7244. this._loadingScreen = loadingScreen;
  7245. },
  7246. enumerable: true,
  7247. configurable: true
  7248. });
  7249. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7250. set: function (text) {
  7251. this._loadingScreen.loadingUIText = text;
  7252. },
  7253. enumerable: true,
  7254. configurable: true
  7255. });
  7256. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7257. set: function (color) {
  7258. this._loadingScreen.loadingUIBackgroundColor = color;
  7259. },
  7260. enumerable: true,
  7261. configurable: true
  7262. });
  7263. // FPS
  7264. Engine.prototype.getFps = function () {
  7265. return this.fps;
  7266. };
  7267. Engine.prototype.getDeltaTime = function () {
  7268. return this.deltaTime;
  7269. };
  7270. Engine.prototype._measureFps = function () {
  7271. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7272. var length = this.previousFramesDuration.length;
  7273. if (length >= 2) {
  7274. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7275. }
  7276. if (length >= this.fpsRange) {
  7277. if (length > this.fpsRange) {
  7278. this.previousFramesDuration.splice(0, 1);
  7279. length = this.previousFramesDuration.length;
  7280. }
  7281. var sum = 0;
  7282. for (var id = 0; id < length - 1; id++) {
  7283. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7284. }
  7285. this.fps = 1000.0 / (sum / (length - 1));
  7286. }
  7287. };
  7288. // Statics
  7289. Engine.isSupported = function () {
  7290. try {
  7291. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7292. if (navigator.isCocoonJS) {
  7293. return true;
  7294. }
  7295. var tempcanvas = document.createElement("canvas");
  7296. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7297. return gl != null && !!window.WebGLRenderingContext;
  7298. }
  7299. catch (e) {
  7300. return false;
  7301. }
  7302. };
  7303. // Const statics
  7304. Engine._ALPHA_DISABLE = 0;
  7305. Engine._ALPHA_ADD = 1;
  7306. Engine._ALPHA_COMBINE = 2;
  7307. Engine._ALPHA_SUBTRACT = 3;
  7308. Engine._ALPHA_MULTIPLY = 4;
  7309. Engine._ALPHA_MAXIMIZED = 5;
  7310. Engine._ALPHA_ONEONE = 6;
  7311. Engine._DELAYLOADSTATE_NONE = 0;
  7312. Engine._DELAYLOADSTATE_LOADED = 1;
  7313. Engine._DELAYLOADSTATE_LOADING = 2;
  7314. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7315. Engine._TEXTUREFORMAT_ALPHA = 0;
  7316. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7317. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7318. Engine._TEXTUREFORMAT_RGB = 4;
  7319. Engine._TEXTUREFORMAT_RGBA = 5;
  7320. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7321. Engine._TEXTURETYPE_FLOAT = 1;
  7322. // Updatable statics so stick with vars here
  7323. Engine.CollisionsEpsilon = 0.001;
  7324. Engine.CodeRepository = "src/";
  7325. Engine.ShadersRepository = "src/Shaders/";
  7326. return Engine;
  7327. })();
  7328. BABYLON.Engine = Engine;
  7329. })(BABYLON || (BABYLON = {}));
  7330. var BABYLON;
  7331. (function (BABYLON) {
  7332. /**
  7333. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7334. */
  7335. var Node = (function () {
  7336. /**
  7337. * @constructor
  7338. * @param {string} name - the name and id to be given to this node
  7339. * @param {BABYLON.Scene} the scene this node will be added to
  7340. */
  7341. function Node(name, scene) {
  7342. this.state = "";
  7343. this.animations = new Array();
  7344. this._ranges = {};
  7345. this._childrenFlag = -1;
  7346. this._isEnabled = true;
  7347. this._isReady = true;
  7348. this._currentRenderId = -1;
  7349. this._parentRenderId = -1;
  7350. this.name = name;
  7351. this.id = name;
  7352. this._scene = scene;
  7353. this._initCache();
  7354. }
  7355. Object.defineProperty(Node.prototype, "parent", {
  7356. get: function () {
  7357. return this._parentNode;
  7358. },
  7359. set: function (parent) {
  7360. if (this._parentNode === parent) {
  7361. return;
  7362. }
  7363. if (this._parentNode) {
  7364. var index = this._parentNode._children.indexOf(this);
  7365. if (index !== -1) {
  7366. this._parentNode._children.splice(index, 1);
  7367. }
  7368. }
  7369. this._parentNode = parent;
  7370. if (this._parentNode) {
  7371. if (!this._parentNode._children) {
  7372. this._parentNode._children = new Array();
  7373. }
  7374. this._parentNode._children.push(this);
  7375. }
  7376. },
  7377. enumerable: true,
  7378. configurable: true
  7379. });
  7380. Node.prototype.getScene = function () {
  7381. return this._scene;
  7382. };
  7383. Node.prototype.getEngine = function () {
  7384. return this._scene.getEngine();
  7385. };
  7386. // override it in derived class
  7387. Node.prototype.getWorldMatrix = function () {
  7388. return BABYLON.Matrix.Identity();
  7389. };
  7390. // override it in derived class if you add new variables to the cache
  7391. // and call the parent class method
  7392. Node.prototype._initCache = function () {
  7393. this._cache = {};
  7394. this._cache.parent = undefined;
  7395. };
  7396. Node.prototype.updateCache = function (force) {
  7397. if (!force && this.isSynchronized())
  7398. return;
  7399. this._cache.parent = this.parent;
  7400. this._updateCache();
  7401. };
  7402. // override it in derived class if you add new variables to the cache
  7403. // and call the parent class method if !ignoreParentClass
  7404. Node.prototype._updateCache = function (ignoreParentClass) {
  7405. };
  7406. // override it in derived class if you add new variables to the cache
  7407. Node.prototype._isSynchronized = function () {
  7408. return true;
  7409. };
  7410. Node.prototype._markSyncedWithParent = function () {
  7411. this._parentRenderId = this.parent._currentRenderId;
  7412. };
  7413. Node.prototype.isSynchronizedWithParent = function () {
  7414. if (!this.parent) {
  7415. return true;
  7416. }
  7417. if (this._parentRenderId !== this.parent._currentRenderId) {
  7418. return false;
  7419. }
  7420. return this.parent.isSynchronized();
  7421. };
  7422. Node.prototype.isSynchronized = function (updateCache) {
  7423. var check = this.hasNewParent();
  7424. check = check || !this.isSynchronizedWithParent();
  7425. check = check || !this._isSynchronized();
  7426. if (updateCache)
  7427. this.updateCache(true);
  7428. return !check;
  7429. };
  7430. Node.prototype.hasNewParent = function (update) {
  7431. if (this._cache.parent === this.parent)
  7432. return false;
  7433. if (update)
  7434. this._cache.parent = this.parent;
  7435. return true;
  7436. };
  7437. /**
  7438. * Is this node ready to be used/rendered
  7439. * @return {boolean} is it ready
  7440. */
  7441. Node.prototype.isReady = function () {
  7442. return this._isReady;
  7443. };
  7444. /**
  7445. * Is this node enabled.
  7446. * If the node has a parent and is enabled, the parent will be inspected as well.
  7447. * @return {boolean} whether this node (and its parent) is enabled.
  7448. * @see setEnabled
  7449. */
  7450. Node.prototype.isEnabled = function () {
  7451. if (!this._isEnabled) {
  7452. return false;
  7453. }
  7454. if (this.parent) {
  7455. return this.parent.isEnabled();
  7456. }
  7457. return true;
  7458. };
  7459. /**
  7460. * Set the enabled state of this node.
  7461. * @param {boolean} value - the new enabled state
  7462. * @see isEnabled
  7463. */
  7464. Node.prototype.setEnabled = function (value) {
  7465. this._isEnabled = value;
  7466. };
  7467. /**
  7468. * Is this node a descendant of the given node.
  7469. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7470. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7471. * @see parent
  7472. */
  7473. Node.prototype.isDescendantOf = function (ancestor) {
  7474. if (this.parent) {
  7475. if (this.parent === ancestor) {
  7476. return true;
  7477. }
  7478. return this.parent.isDescendantOf(ancestor);
  7479. }
  7480. return false;
  7481. };
  7482. /**
  7483. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7484. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7485. * @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.
  7486. * @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.
  7487. */
  7488. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7489. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7490. if (!this._children) {
  7491. return;
  7492. }
  7493. for (var index = 0; index < this._children.length; index++) {
  7494. var item = this._children[index];
  7495. if (!predicate || predicate(item)) {
  7496. results.push(item);
  7497. }
  7498. if (!directDescendantsOnly) {
  7499. item._getDescendants(results, false, predicate);
  7500. }
  7501. }
  7502. };
  7503. /**
  7504. * Will return all nodes that have this node as ascendant.
  7505. * @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.
  7506. * @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.
  7507. * @return {BABYLON.Node[]} all children nodes of all types.
  7508. */
  7509. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7510. var results = [];
  7511. this._getDescendants(results, directDescendantsOnly, predicate);
  7512. return results;
  7513. };
  7514. /**
  7515. * @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.
  7516. * @Deprecated, legacy support.
  7517. * use getDecendants instead.
  7518. */
  7519. Node.prototype.getChildren = function (predicate) {
  7520. return this.getDescendants(true, predicate);
  7521. };
  7522. /**
  7523. * Get all child-meshes of this node.
  7524. */
  7525. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7526. var results = [];
  7527. this._getDescendants(results, directDecendantsOnly, function (node) {
  7528. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7529. });
  7530. return results;
  7531. };
  7532. Node.prototype._setReady = function (state) {
  7533. if (state === this._isReady) {
  7534. return;
  7535. }
  7536. if (!state) {
  7537. this._isReady = false;
  7538. return;
  7539. }
  7540. this._isReady = true;
  7541. if (this.onReady) {
  7542. this.onReady(this);
  7543. }
  7544. };
  7545. Node.prototype.getAnimationByName = function (name) {
  7546. for (var i = 0; i < this.animations.length; i++) {
  7547. var animation = this.animations[i];
  7548. if (animation.name === name) {
  7549. return animation;
  7550. }
  7551. }
  7552. return null;
  7553. };
  7554. Node.prototype.createAnimationRange = function (name, from, to) {
  7555. // check name not already in use
  7556. if (!this._ranges[name]) {
  7557. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7558. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7559. if (this.animations[i]) {
  7560. this.animations[i].createRange(name, from, to);
  7561. }
  7562. }
  7563. }
  7564. };
  7565. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7566. if (deleteFrames === void 0) { deleteFrames = true; }
  7567. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7568. if (this.animations[i]) {
  7569. this.animations[i].deleteRange(name, deleteFrames);
  7570. }
  7571. }
  7572. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7573. };
  7574. Node.prototype.getAnimationRange = function (name) {
  7575. return this._ranges[name];
  7576. };
  7577. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7578. var range = this.getAnimationRange(name);
  7579. if (!range) {
  7580. return null;
  7581. }
  7582. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7583. };
  7584. Node.prototype.serializeAnimationRanges = function () {
  7585. var serializationRanges = [];
  7586. for (var name in this._ranges) {
  7587. var range = {};
  7588. range.name = name;
  7589. range.from = this._ranges[name].from;
  7590. range.to = this._ranges[name].to;
  7591. serializationRanges.push(range);
  7592. }
  7593. return serializationRanges;
  7594. };
  7595. Node.prototype.dispose = function () {
  7596. this.parent = null;
  7597. };
  7598. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7599. if (parsedNode.ranges) {
  7600. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7601. var data = parsedNode.ranges[index];
  7602. node.createAnimationRange(data.name, data.from, data.to);
  7603. }
  7604. }
  7605. };
  7606. __decorate([
  7607. BABYLON.serialize()
  7608. ], Node.prototype, "name", void 0);
  7609. __decorate([
  7610. BABYLON.serialize()
  7611. ], Node.prototype, "id", void 0);
  7612. __decorate([
  7613. BABYLON.serialize()
  7614. ], Node.prototype, "uniqueId", void 0);
  7615. __decorate([
  7616. BABYLON.serialize()
  7617. ], Node.prototype, "state", void 0);
  7618. return Node;
  7619. })();
  7620. BABYLON.Node = Node;
  7621. })(BABYLON || (BABYLON = {}));
  7622. var BABYLON;
  7623. (function (BABYLON) {
  7624. var FilesInput = (function () {
  7625. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7626. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7627. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7628. this._engine = p_engine;
  7629. this._canvas = p_canvas;
  7630. this._currentScene = p_scene;
  7631. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7632. this._progressCallback = p_progressCallback;
  7633. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7634. this._textureLoadingCallback = p_textureLoadingCallback;
  7635. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7636. }
  7637. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7638. var _this = this;
  7639. if (p_elementToMonitor) {
  7640. this._elementToMonitor = p_elementToMonitor;
  7641. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7642. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7643. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7644. }
  7645. };
  7646. FilesInput.prototype.renderFunction = function () {
  7647. if (this._additionnalRenderLoopLogicCallback) {
  7648. this._additionnalRenderLoopLogicCallback();
  7649. }
  7650. if (this._currentScene) {
  7651. if (this._textureLoadingCallback) {
  7652. var remaining = this._currentScene.getWaitingItemsCount();
  7653. if (remaining > 0) {
  7654. this._textureLoadingCallback(remaining);
  7655. }
  7656. }
  7657. this._currentScene.render();
  7658. }
  7659. };
  7660. FilesInput.prototype.drag = function (e) {
  7661. e.stopPropagation();
  7662. e.preventDefault();
  7663. };
  7664. FilesInput.prototype.drop = function (eventDrop) {
  7665. eventDrop.stopPropagation();
  7666. eventDrop.preventDefault();
  7667. this.loadFiles(eventDrop);
  7668. };
  7669. FilesInput.prototype.loadFiles = function (event) {
  7670. if (this._startingProcessingFilesCallback)
  7671. this._startingProcessingFilesCallback();
  7672. // Handling data transfer via drag'n'drop
  7673. if (event && event.dataTransfer && event.dataTransfer.files) {
  7674. this._filesToLoad = event.dataTransfer.files;
  7675. }
  7676. // Handling files from input files
  7677. if (event && event.target && event.target.files) {
  7678. this._filesToLoad = event.target.files;
  7679. }
  7680. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7681. for (var i = 0; i < this._filesToLoad.length; i++) {
  7682. switch (this._filesToLoad[i].type) {
  7683. case "image/jpeg":
  7684. case "image/png":
  7685. case "image/bmp":
  7686. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7687. break;
  7688. case "image/targa":
  7689. case "image/vnd.ms-dds":
  7690. case "audio/wav":
  7691. case "audio/x-wav":
  7692. case "audio/mp3":
  7693. case "audio/mpeg":
  7694. case "audio/mpeg3":
  7695. case "audio/x-mpeg-3":
  7696. case "audio/ogg":
  7697. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7698. break;
  7699. default:
  7700. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7701. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7702. }
  7703. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7704. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7705. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7706. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7707. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7708. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7709. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7710. this._sceneFileToLoad = this._filesToLoad[i];
  7711. }
  7712. break;
  7713. }
  7714. }
  7715. this.reload();
  7716. }
  7717. };
  7718. FilesInput.prototype.reload = function () {
  7719. var _this = this;
  7720. var that = this;
  7721. // If a ".babylon" file has been provided
  7722. if (this._sceneFileToLoad) {
  7723. if (this._currentScene) {
  7724. if (BABYLON.Tools.errorsCount > 0) {
  7725. BABYLON.Tools.ClearLogCache();
  7726. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7727. }
  7728. this._engine.stopRenderLoop();
  7729. this._currentScene.dispose();
  7730. }
  7731. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7732. that._currentScene = newScene;
  7733. // Wait for textures and shaders to be ready
  7734. that._currentScene.executeWhenReady(function () {
  7735. // Attach camera to canvas inputs
  7736. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7737. that._currentScene.createDefaultCameraOrLight();
  7738. }
  7739. that._currentScene.activeCamera.attachControl(that._canvas);
  7740. if (that._sceneLoadedCallback) {
  7741. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7742. }
  7743. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7744. });
  7745. }, function (progress) {
  7746. if (_this._progressCallback) {
  7747. _this._progressCallback(progress);
  7748. }
  7749. });
  7750. }
  7751. else {
  7752. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7753. }
  7754. };
  7755. FilesInput.FilesTextures = new Array();
  7756. FilesInput.FilesToLoad = new Array();
  7757. return FilesInput;
  7758. })();
  7759. BABYLON.FilesInput = FilesInput;
  7760. })(BABYLON || (BABYLON = {}));
  7761. var BABYLON;
  7762. (function (BABYLON) {
  7763. var IntersectionInfo = (function () {
  7764. function IntersectionInfo(bu, bv, distance) {
  7765. this.bu = bu;
  7766. this.bv = bv;
  7767. this.distance = distance;
  7768. this.faceId = 0;
  7769. this.subMeshId = 0;
  7770. }
  7771. return IntersectionInfo;
  7772. })();
  7773. BABYLON.IntersectionInfo = IntersectionInfo;
  7774. var PickingInfo = (function () {
  7775. function PickingInfo() {
  7776. this.hit = false;
  7777. this.distance = 0;
  7778. this.pickedPoint = null;
  7779. this.pickedMesh = null;
  7780. this.bu = 0;
  7781. this.bv = 0;
  7782. this.faceId = -1;
  7783. this.subMeshId = 0;
  7784. this.pickedSprite = null;
  7785. }
  7786. // Methods
  7787. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7788. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7789. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7790. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7791. return null;
  7792. }
  7793. var indices = this.pickedMesh.getIndices();
  7794. var result;
  7795. if (useVerticesNormals) {
  7796. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7797. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7798. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7799. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7800. normal0 = normal0.scale(this.bu);
  7801. normal1 = normal1.scale(this.bv);
  7802. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7803. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7804. }
  7805. else {
  7806. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7807. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7808. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7809. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7810. var p1p2 = vertex1.subtract(vertex2);
  7811. var p3p2 = vertex3.subtract(vertex2);
  7812. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7813. }
  7814. if (useWorldCoordinates) {
  7815. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7816. }
  7817. return BABYLON.Vector3.Normalize(result);
  7818. };
  7819. PickingInfo.prototype.getTextureCoordinates = function () {
  7820. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7821. return null;
  7822. }
  7823. var indices = this.pickedMesh.getIndices();
  7824. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7825. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7826. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7827. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7828. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7829. uv1 = uv1.scale(this.bu);
  7830. uv2 = uv2.scale(this.bv);
  7831. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7832. };
  7833. return PickingInfo;
  7834. })();
  7835. BABYLON.PickingInfo = PickingInfo;
  7836. })(BABYLON || (BABYLON = {}));
  7837. var BABYLON;
  7838. (function (BABYLON) {
  7839. var BoundingSphere = (function () {
  7840. function BoundingSphere(minimum, maximum) {
  7841. this.minimum = minimum;
  7842. this.maximum = maximum;
  7843. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7844. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7845. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7846. this.radius = distance * 0.5;
  7847. this.centerWorld = BABYLON.Vector3.Zero();
  7848. this._update(BABYLON.Matrix.Identity());
  7849. }
  7850. // Methods
  7851. BoundingSphere.prototype._update = function (world) {
  7852. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7853. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7854. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7855. };
  7856. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7857. for (var i = 0; i < 6; i++) {
  7858. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7859. return false;
  7860. }
  7861. return true;
  7862. };
  7863. BoundingSphere.prototype.intersectsPoint = function (point) {
  7864. var x = this.centerWorld.x - point.x;
  7865. var y = this.centerWorld.y - point.y;
  7866. var z = this.centerWorld.z - point.z;
  7867. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7868. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7869. return false;
  7870. return true;
  7871. };
  7872. // Statics
  7873. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7874. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7875. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7876. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7877. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7878. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7879. return false;
  7880. return true;
  7881. };
  7882. return BoundingSphere;
  7883. })();
  7884. BABYLON.BoundingSphere = BoundingSphere;
  7885. })(BABYLON || (BABYLON = {}));
  7886. var BABYLON;
  7887. (function (BABYLON) {
  7888. var BoundingBox = (function () {
  7889. function BoundingBox(minimum, maximum) {
  7890. this.minimum = minimum;
  7891. this.maximum = maximum;
  7892. this.vectors = new Array();
  7893. this.vectorsWorld = new Array();
  7894. // Bounding vectors
  7895. this.vectors.push(this.minimum.clone());
  7896. this.vectors.push(this.maximum.clone());
  7897. this.vectors.push(this.minimum.clone());
  7898. this.vectors[2].x = this.maximum.x;
  7899. this.vectors.push(this.minimum.clone());
  7900. this.vectors[3].y = this.maximum.y;
  7901. this.vectors.push(this.minimum.clone());
  7902. this.vectors[4].z = this.maximum.z;
  7903. this.vectors.push(this.maximum.clone());
  7904. this.vectors[5].z = this.minimum.z;
  7905. this.vectors.push(this.maximum.clone());
  7906. this.vectors[6].x = this.minimum.x;
  7907. this.vectors.push(this.maximum.clone());
  7908. this.vectors[7].y = this.minimum.y;
  7909. // OBB
  7910. this.center = this.maximum.add(this.minimum).scale(0.5);
  7911. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7912. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7913. // World
  7914. for (var index = 0; index < this.vectors.length; index++) {
  7915. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7916. }
  7917. this.minimumWorld = BABYLON.Vector3.Zero();
  7918. this.maximumWorld = BABYLON.Vector3.Zero();
  7919. this._update(BABYLON.Matrix.Identity());
  7920. }
  7921. // Methods
  7922. BoundingBox.prototype.getWorldMatrix = function () {
  7923. return this._worldMatrix;
  7924. };
  7925. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7926. this._worldMatrix.copyFrom(matrix);
  7927. return this;
  7928. };
  7929. BoundingBox.prototype._update = function (world) {
  7930. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7931. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7932. for (var index = 0; index < this.vectors.length; index++) {
  7933. var v = this.vectorsWorld[index];
  7934. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7935. if (v.x < this.minimumWorld.x)
  7936. this.minimumWorld.x = v.x;
  7937. if (v.y < this.minimumWorld.y)
  7938. this.minimumWorld.y = v.y;
  7939. if (v.z < this.minimumWorld.z)
  7940. this.minimumWorld.z = v.z;
  7941. if (v.x > this.maximumWorld.x)
  7942. this.maximumWorld.x = v.x;
  7943. if (v.y > this.maximumWorld.y)
  7944. this.maximumWorld.y = v.y;
  7945. if (v.z > this.maximumWorld.z)
  7946. this.maximumWorld.z = v.z;
  7947. }
  7948. // OBB
  7949. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7950. this.center.scaleInPlace(0.5);
  7951. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7952. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7953. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7954. this._worldMatrix = world;
  7955. };
  7956. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7957. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7958. };
  7959. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7960. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7961. };
  7962. BoundingBox.prototype.intersectsPoint = function (point) {
  7963. var delta = -BABYLON.Epsilon;
  7964. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7965. return false;
  7966. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7967. return false;
  7968. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7969. return false;
  7970. return true;
  7971. };
  7972. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7973. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7974. };
  7975. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7976. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7977. return false;
  7978. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7979. return false;
  7980. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7981. return false;
  7982. return true;
  7983. };
  7984. // Statics
  7985. BoundingBox.Intersects = function (box0, box1) {
  7986. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7987. return false;
  7988. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7989. return false;
  7990. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7991. return false;
  7992. return true;
  7993. };
  7994. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7995. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7996. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7997. return (num <= (sphereRadius * sphereRadius));
  7998. };
  7999. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  8000. for (var p = 0; p < 6; p++) {
  8001. for (var i = 0; i < 8; i++) {
  8002. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8003. return false;
  8004. }
  8005. }
  8006. }
  8007. return true;
  8008. };
  8009. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  8010. for (var p = 0; p < 6; p++) {
  8011. var inCount = 8;
  8012. for (var i = 0; i < 8; i++) {
  8013. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  8014. --inCount;
  8015. }
  8016. else {
  8017. break;
  8018. }
  8019. }
  8020. if (inCount === 0)
  8021. return false;
  8022. }
  8023. return true;
  8024. };
  8025. return BoundingBox;
  8026. })();
  8027. BABYLON.BoundingBox = BoundingBox;
  8028. })(BABYLON || (BABYLON = {}));
  8029. var BABYLON;
  8030. (function (BABYLON) {
  8031. var computeBoxExtents = function (axis, box) {
  8032. var p = BABYLON.Vector3.Dot(box.center, axis);
  8033. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  8034. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  8035. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  8036. var r = r0 + r1 + r2;
  8037. return {
  8038. min: p - r,
  8039. max: p + r
  8040. };
  8041. };
  8042. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  8043. var axisOverlap = function (axis, box0, box1) {
  8044. var result0 = computeBoxExtents(axis, box0);
  8045. var result1 = computeBoxExtents(axis, box1);
  8046. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  8047. };
  8048. var BoundingInfo = (function () {
  8049. function BoundingInfo(minimum, maximum) {
  8050. this.minimum = minimum;
  8051. this.maximum = maximum;
  8052. this._isLocked = false;
  8053. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  8054. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  8055. }
  8056. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  8057. get: function () {
  8058. return this._isLocked;
  8059. },
  8060. set: function (value) {
  8061. this._isLocked = value;
  8062. },
  8063. enumerable: true,
  8064. configurable: true
  8065. });
  8066. // Methods
  8067. BoundingInfo.prototype.update = function (world) {
  8068. if (this._isLocked) {
  8069. return;
  8070. }
  8071. this.boundingBox._update(world);
  8072. this.boundingSphere._update(world);
  8073. };
  8074. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  8075. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8076. return false;
  8077. return this.boundingBox.isInFrustum(frustumPlanes);
  8078. };
  8079. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8080. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8081. };
  8082. BoundingInfo.prototype._checkCollision = function (collider) {
  8083. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8084. };
  8085. BoundingInfo.prototype.intersectsPoint = function (point) {
  8086. if (!this.boundingSphere.centerWorld) {
  8087. return false;
  8088. }
  8089. if (!this.boundingSphere.intersectsPoint(point)) {
  8090. return false;
  8091. }
  8092. if (!this.boundingBox.intersectsPoint(point)) {
  8093. return false;
  8094. }
  8095. return true;
  8096. };
  8097. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8098. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8099. return false;
  8100. }
  8101. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8102. return false;
  8103. }
  8104. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8105. return false;
  8106. }
  8107. if (!precise) {
  8108. return true;
  8109. }
  8110. var box0 = this.boundingBox;
  8111. var box1 = boundingInfo.boundingBox;
  8112. if (!axisOverlap(box0.directions[0], box0, box1))
  8113. return false;
  8114. if (!axisOverlap(box0.directions[1], box0, box1))
  8115. return false;
  8116. if (!axisOverlap(box0.directions[2], box0, box1))
  8117. return false;
  8118. if (!axisOverlap(box1.directions[0], box0, box1))
  8119. return false;
  8120. if (!axisOverlap(box1.directions[1], box0, box1))
  8121. return false;
  8122. if (!axisOverlap(box1.directions[2], box0, box1))
  8123. return false;
  8124. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8125. return false;
  8126. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8127. return false;
  8128. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8129. return false;
  8130. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8131. return false;
  8132. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8133. return false;
  8134. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8135. return false;
  8136. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8137. return false;
  8138. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8139. return false;
  8140. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8141. return false;
  8142. return true;
  8143. };
  8144. return BoundingInfo;
  8145. })();
  8146. BABYLON.BoundingInfo = BoundingInfo;
  8147. })(BABYLON || (BABYLON = {}));
  8148. var BABYLON;
  8149. (function (BABYLON) {
  8150. var Ray = (function () {
  8151. function Ray(origin, direction, length) {
  8152. if (length === void 0) { length = Number.MAX_VALUE; }
  8153. this.origin = origin;
  8154. this.direction = direction;
  8155. this.length = length;
  8156. }
  8157. // Methods
  8158. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8159. var d = 0.0;
  8160. var maxValue = Number.MAX_VALUE;
  8161. var inv;
  8162. var min;
  8163. var max;
  8164. var temp;
  8165. if (Math.abs(this.direction.x) < 0.0000001) {
  8166. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8167. return false;
  8168. }
  8169. }
  8170. else {
  8171. inv = 1.0 / this.direction.x;
  8172. min = (minimum.x - this.origin.x) * inv;
  8173. max = (maximum.x - this.origin.x) * inv;
  8174. if (max === -Infinity) {
  8175. max = Infinity;
  8176. }
  8177. if (min > max) {
  8178. temp = min;
  8179. min = max;
  8180. max = temp;
  8181. }
  8182. d = Math.max(min, d);
  8183. maxValue = Math.min(max, maxValue);
  8184. if (d > maxValue) {
  8185. return false;
  8186. }
  8187. }
  8188. if (Math.abs(this.direction.y) < 0.0000001) {
  8189. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8190. return false;
  8191. }
  8192. }
  8193. else {
  8194. inv = 1.0 / this.direction.y;
  8195. min = (minimum.y - this.origin.y) * inv;
  8196. max = (maximum.y - this.origin.y) * inv;
  8197. if (max === -Infinity) {
  8198. max = Infinity;
  8199. }
  8200. if (min > max) {
  8201. temp = min;
  8202. min = max;
  8203. max = temp;
  8204. }
  8205. d = Math.max(min, d);
  8206. maxValue = Math.min(max, maxValue);
  8207. if (d > maxValue) {
  8208. return false;
  8209. }
  8210. }
  8211. if (Math.abs(this.direction.z) < 0.0000001) {
  8212. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8213. return false;
  8214. }
  8215. }
  8216. else {
  8217. inv = 1.0 / this.direction.z;
  8218. min = (minimum.z - this.origin.z) * inv;
  8219. max = (maximum.z - this.origin.z) * inv;
  8220. if (max === -Infinity) {
  8221. max = Infinity;
  8222. }
  8223. if (min > max) {
  8224. temp = min;
  8225. min = max;
  8226. max = temp;
  8227. }
  8228. d = Math.max(min, d);
  8229. maxValue = Math.min(max, maxValue);
  8230. if (d > maxValue) {
  8231. return false;
  8232. }
  8233. }
  8234. return true;
  8235. };
  8236. Ray.prototype.intersectsBox = function (box) {
  8237. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8238. };
  8239. Ray.prototype.intersectsSphere = function (sphere) {
  8240. var x = sphere.center.x - this.origin.x;
  8241. var y = sphere.center.y - this.origin.y;
  8242. var z = sphere.center.z - this.origin.z;
  8243. var pyth = (x * x) + (y * y) + (z * z);
  8244. var rr = sphere.radius * sphere.radius;
  8245. if (pyth <= rr) {
  8246. return true;
  8247. }
  8248. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8249. if (dot < 0.0) {
  8250. return false;
  8251. }
  8252. var temp = pyth - (dot * dot);
  8253. return temp <= rr;
  8254. };
  8255. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8256. if (!this._edge1) {
  8257. this._edge1 = BABYLON.Vector3.Zero();
  8258. this._edge2 = BABYLON.Vector3.Zero();
  8259. this._pvec = BABYLON.Vector3.Zero();
  8260. this._tvec = BABYLON.Vector3.Zero();
  8261. this._qvec = BABYLON.Vector3.Zero();
  8262. }
  8263. vertex1.subtractToRef(vertex0, this._edge1);
  8264. vertex2.subtractToRef(vertex0, this._edge2);
  8265. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8266. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8267. if (det === 0) {
  8268. return null;
  8269. }
  8270. var invdet = 1 / det;
  8271. this.origin.subtractToRef(vertex0, this._tvec);
  8272. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8273. if (bu < 0 || bu > 1.0) {
  8274. return null;
  8275. }
  8276. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8277. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8278. if (bv < 0 || bu + bv > 1.0) {
  8279. return null;
  8280. }
  8281. //check if the distance is longer than the predefined length.
  8282. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8283. if (distance > this.length) {
  8284. return null;
  8285. }
  8286. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8287. };
  8288. Ray.prototype.intersectsPlane = function (plane) {
  8289. var distance;
  8290. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8291. if (Math.abs(result1) < 9.99999997475243E-07) {
  8292. return null;
  8293. }
  8294. else {
  8295. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8296. distance = (-plane.d - result2) / result1;
  8297. if (distance < 0.0) {
  8298. if (distance < -9.99999997475243E-07) {
  8299. return null;
  8300. }
  8301. else {
  8302. return 0;
  8303. }
  8304. }
  8305. return distance;
  8306. }
  8307. };
  8308. /**
  8309. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8310. * @param sega the first point of the segment to test the intersection against
  8311. * @param segb the second point of the segment to test the intersection against
  8312. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8313. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8314. */
  8315. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8316. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8317. var u = segb.subtract(sega);
  8318. var v = rsegb.subtract(this.origin);
  8319. var w = sega.subtract(this.origin);
  8320. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8321. var b = BABYLON.Vector3.Dot(u, v);
  8322. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8323. var d = BABYLON.Vector3.Dot(u, w);
  8324. var e = BABYLON.Vector3.Dot(v, w);
  8325. var D = a * c - b * b; // always >= 0
  8326. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8327. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8328. // compute the line parameters of the two closest points
  8329. if (D < Ray.smallnum) {
  8330. sN = 0.0; // force using point P0 on segment S1
  8331. sD = 1.0; // to prevent possible division by 0.0 later
  8332. tN = e;
  8333. tD = c;
  8334. }
  8335. else {
  8336. sN = (b * e - c * d);
  8337. tN = (a * e - b * d);
  8338. if (sN < 0.0) {
  8339. sN = 0.0;
  8340. tN = e;
  8341. tD = c;
  8342. }
  8343. else if (sN > sD) {
  8344. sN = sD;
  8345. tN = e + b;
  8346. tD = c;
  8347. }
  8348. }
  8349. if (tN < 0.0) {
  8350. tN = 0.0;
  8351. // recompute sc for this edge
  8352. if (-d < 0.0) {
  8353. sN = 0.0;
  8354. }
  8355. else if (-d > a)
  8356. sN = sD;
  8357. else {
  8358. sN = -d;
  8359. sD = a;
  8360. }
  8361. }
  8362. else if (tN > tD) {
  8363. tN = tD;
  8364. // recompute sc for this edge
  8365. if ((-d + b) < 0.0) {
  8366. sN = 0;
  8367. }
  8368. else if ((-d + b) > a) {
  8369. sN = sD;
  8370. }
  8371. else {
  8372. sN = (-d + b);
  8373. sD = a;
  8374. }
  8375. }
  8376. // finally do the division to get sc and tc
  8377. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8378. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8379. // get the difference of the two closest points
  8380. var qtc = v.multiplyByFloats(tc, tc, tc);
  8381. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8382. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8383. if (isIntersected) {
  8384. return qtc.length();
  8385. }
  8386. return -1;
  8387. };
  8388. // Statics
  8389. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8390. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8391. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8392. var direction = end.subtract(start);
  8393. direction.normalize();
  8394. return new Ray(start, direction);
  8395. };
  8396. /**
  8397. * 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
  8398. * transformed to the given world matrix.
  8399. * @param origin The origin point
  8400. * @param end The end point
  8401. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8402. */
  8403. Ray.CreateNewFromTo = function (origin, end, world) {
  8404. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8405. var direction = end.subtract(origin);
  8406. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8407. direction.normalize();
  8408. return Ray.Transform(new Ray(origin, direction, length), world);
  8409. };
  8410. Ray.Transform = function (ray, matrix) {
  8411. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8412. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8413. newDirection.normalize();
  8414. return new Ray(newOrigin, newDirection, ray.length);
  8415. };
  8416. Ray.smallnum = 0.00000001;
  8417. Ray.rayl = 10e8;
  8418. return Ray;
  8419. })();
  8420. BABYLON.Ray = Ray;
  8421. })(BABYLON || (BABYLON = {}));
  8422. var BABYLON;
  8423. (function (BABYLON) {
  8424. var AbstractMesh = (function (_super) {
  8425. __extends(AbstractMesh, _super);
  8426. // Constructor
  8427. function AbstractMesh(name, scene) {
  8428. var _this = this;
  8429. _super.call(this, name, scene);
  8430. // Events
  8431. /**
  8432. * An event triggered when this mesh collides with another one
  8433. * @type {BABYLON.Observable}
  8434. */
  8435. this.onCollideObservable = new BABYLON.Observable();
  8436. /**
  8437. * An event triggered when the collision's position changes
  8438. * @type {BABYLON.Observable}
  8439. */
  8440. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8441. /**
  8442. * An event triggered after the world matrix is updated
  8443. * @type {BABYLON.Observable}
  8444. */
  8445. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8446. // Properties
  8447. this.definedFacingForward = true; // orientation for POV movement & rotation
  8448. this.position = new BABYLON.Vector3(0, 0, 0);
  8449. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8450. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8451. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8452. this.visibility = 1.0;
  8453. this.alphaIndex = Number.MAX_VALUE;
  8454. this.infiniteDistance = false;
  8455. this.isVisible = true;
  8456. this.isPickable = true;
  8457. this.showBoundingBox = false;
  8458. this.showSubMeshesBoundingBox = false;
  8459. this.onDispose = null;
  8460. this.isBlocker = false;
  8461. this.renderingGroupId = 0;
  8462. this.receiveShadows = false;
  8463. this.renderOutline = false;
  8464. this.outlineColor = BABYLON.Color3.Red();
  8465. this.outlineWidth = 0.02;
  8466. this.renderOverlay = false;
  8467. this.overlayColor = BABYLON.Color3.Red();
  8468. this.overlayAlpha = 0.5;
  8469. this.hasVertexAlpha = false;
  8470. this.useVertexColors = true;
  8471. this.applyFog = true;
  8472. this.computeBonesUsingShaders = true;
  8473. this.scalingDeterminant = 1;
  8474. this.numBoneInfluencers = 4;
  8475. this.useOctreeForRenderingSelection = true;
  8476. this.useOctreeForPicking = true;
  8477. this.useOctreeForCollisions = true;
  8478. this.layerMask = 0x0FFFFFFF;
  8479. this.alwaysSelectAsActiveMesh = false;
  8480. // Collisions
  8481. this._checkCollisions = false;
  8482. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8483. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8484. this._collider = new BABYLON.Collider();
  8485. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8486. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8487. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8488. // Edges
  8489. this.edgesWidth = 1;
  8490. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8491. // Cache
  8492. this._localWorld = BABYLON.Matrix.Zero();
  8493. this._worldMatrix = BABYLON.Matrix.Zero();
  8494. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8495. this._absolutePosition = BABYLON.Vector3.Zero();
  8496. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8497. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8498. this._isDirty = false;
  8499. this._pivotMatrix = BABYLON.Matrix.Identity();
  8500. this._isDisposed = false;
  8501. this._renderId = 0;
  8502. this._intersectionsInProgress = new Array();
  8503. this._isWorldMatrixFrozen = false;
  8504. this._unIndexed = false;
  8505. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8506. if (collidedMesh === void 0) { collidedMesh = null; }
  8507. //TODO move this to the collision coordinator!
  8508. if (_this.getScene().workerCollisions)
  8509. newPosition.multiplyInPlace(_this._collider.radius);
  8510. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8511. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8512. _this.position.addInPlace(_this._diffPositionForCollisions);
  8513. }
  8514. if (collidedMesh) {
  8515. _this.onCollideObservable.notifyObservers(collidedMesh);
  8516. }
  8517. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8518. };
  8519. scene.addMesh(this);
  8520. }
  8521. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8522. get: function () {
  8523. return AbstractMesh._BILLBOARDMODE_NONE;
  8524. },
  8525. enumerable: true,
  8526. configurable: true
  8527. });
  8528. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8529. get: function () {
  8530. return AbstractMesh._BILLBOARDMODE_X;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8536. get: function () {
  8537. return AbstractMesh._BILLBOARDMODE_Y;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8543. get: function () {
  8544. return AbstractMesh._BILLBOARDMODE_Z;
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8550. get: function () {
  8551. return AbstractMesh._BILLBOARDMODE_ALL;
  8552. },
  8553. enumerable: true,
  8554. configurable: true
  8555. });
  8556. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8557. set: function (callback) {
  8558. if (this._onCollideObserver) {
  8559. this.onCollideObservable.remove(this._onCollideObserver);
  8560. }
  8561. this._onCollideObserver = this.onCollideObservable.add(callback);
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8567. set: function (callback) {
  8568. if (this._onCollisionPositionChangeObserver) {
  8569. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8570. }
  8571. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8572. },
  8573. enumerable: true,
  8574. configurable: true
  8575. });
  8576. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8577. get: function () {
  8578. return this._skeleton;
  8579. },
  8580. set: function (value) {
  8581. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8582. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8583. }
  8584. if (value && value.needInitialSkinMatrix) {
  8585. value._registerMeshWithPoseMatrix(this);
  8586. }
  8587. this._skeleton = value;
  8588. if (!this._skeleton) {
  8589. this._bonesTransformMatrices = null;
  8590. }
  8591. },
  8592. enumerable: true,
  8593. configurable: true
  8594. });
  8595. /**
  8596. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8597. */
  8598. AbstractMesh.prototype.toString = function (fullDetails) {
  8599. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8600. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8601. if (this._skeleton) {
  8602. ret += ", skeleton: " + this._skeleton.name;
  8603. }
  8604. if (fullDetails) {
  8605. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8606. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8607. }
  8608. return ret;
  8609. };
  8610. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8611. /**
  8612. * Getting the rotation object.
  8613. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8614. */
  8615. get: function () {
  8616. return this._rotation;
  8617. },
  8618. set: function (newRotation) {
  8619. this._rotation = newRotation;
  8620. },
  8621. enumerable: true,
  8622. configurable: true
  8623. });
  8624. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8625. get: function () {
  8626. return this._scaling;
  8627. },
  8628. set: function (newScaling) {
  8629. this._scaling = newScaling;
  8630. if (this.physicsImpostor) {
  8631. this.physicsImpostor.forceUpdate();
  8632. }
  8633. },
  8634. enumerable: true,
  8635. configurable: true
  8636. });
  8637. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8638. get: function () {
  8639. return this._rotationQuaternion;
  8640. },
  8641. set: function (quaternion) {
  8642. this._rotationQuaternion = quaternion;
  8643. //reset the rotation vector.
  8644. if (quaternion && this.rotation.length()) {
  8645. this.rotation.copyFromFloats(0, 0, 0);
  8646. }
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. // Methods
  8652. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8653. this._poseMatrix.copyFrom(matrix);
  8654. };
  8655. AbstractMesh.prototype.getPoseMatrix = function () {
  8656. return this._poseMatrix;
  8657. };
  8658. AbstractMesh.prototype.disableEdgesRendering = function () {
  8659. if (this._edgesRenderer !== undefined) {
  8660. this._edgesRenderer.dispose();
  8661. this._edgesRenderer = undefined;
  8662. }
  8663. };
  8664. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8665. if (epsilon === void 0) { epsilon = 0.95; }
  8666. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8667. this.disableEdgesRendering();
  8668. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8669. };
  8670. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8671. get: function () {
  8672. return false;
  8673. },
  8674. enumerable: true,
  8675. configurable: true
  8676. });
  8677. AbstractMesh.prototype.getLOD = function (camera) {
  8678. return this;
  8679. };
  8680. AbstractMesh.prototype.getTotalVertices = function () {
  8681. return 0;
  8682. };
  8683. AbstractMesh.prototype.getIndices = function () {
  8684. return null;
  8685. };
  8686. AbstractMesh.prototype.getVerticesData = function (kind) {
  8687. return null;
  8688. };
  8689. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8690. return false;
  8691. };
  8692. AbstractMesh.prototype.getBoundingInfo = function () {
  8693. if (this._masterMesh) {
  8694. return this._masterMesh.getBoundingInfo();
  8695. }
  8696. if (!this._boundingInfo) {
  8697. this._updateBoundingInfo();
  8698. }
  8699. return this._boundingInfo;
  8700. };
  8701. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8702. get: function () {
  8703. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8704. },
  8705. enumerable: true,
  8706. configurable: true
  8707. });
  8708. AbstractMesh.prototype._preActivate = function () {
  8709. };
  8710. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8711. };
  8712. AbstractMesh.prototype._activate = function (renderId) {
  8713. this._renderId = renderId;
  8714. };
  8715. AbstractMesh.prototype.getWorldMatrix = function () {
  8716. if (this._masterMesh) {
  8717. return this._masterMesh.getWorldMatrix();
  8718. }
  8719. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8720. this.computeWorldMatrix();
  8721. }
  8722. return this._worldMatrix;
  8723. };
  8724. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8725. get: function () {
  8726. return this._worldMatrix;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8732. get: function () {
  8733. return this._absolutePosition;
  8734. },
  8735. enumerable: true,
  8736. configurable: true
  8737. });
  8738. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8739. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8740. this.computeWorldMatrix(true);
  8741. this._isWorldMatrixFrozen = true;
  8742. };
  8743. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8744. this._isWorldMatrixFrozen = false;
  8745. this.computeWorldMatrix(true);
  8746. };
  8747. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8748. get: function () {
  8749. return this._isWorldMatrixFrozen;
  8750. },
  8751. enumerable: true,
  8752. configurable: true
  8753. });
  8754. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8755. axis.normalize();
  8756. if (!this.rotationQuaternion) {
  8757. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8758. this.rotation = BABYLON.Vector3.Zero();
  8759. }
  8760. var rotationQuaternion;
  8761. if (!space || space === BABYLON.Space.LOCAL) {
  8762. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8763. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8764. }
  8765. else {
  8766. if (this.parent) {
  8767. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8768. invertParentWorldMatrix.invert();
  8769. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8770. }
  8771. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8772. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8773. }
  8774. };
  8775. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8776. var displacementVector = axis.scale(distance);
  8777. if (!space || space === BABYLON.Space.LOCAL) {
  8778. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8779. this.setPositionWithLocalVector(tempV3);
  8780. }
  8781. else {
  8782. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8783. }
  8784. };
  8785. AbstractMesh.prototype.getAbsolutePosition = function () {
  8786. this.computeWorldMatrix();
  8787. return this._absolutePosition;
  8788. };
  8789. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8790. if (!absolutePosition) {
  8791. return;
  8792. }
  8793. var absolutePositionX;
  8794. var absolutePositionY;
  8795. var absolutePositionZ;
  8796. if (absolutePosition.x === undefined) {
  8797. if (arguments.length < 3) {
  8798. return;
  8799. }
  8800. absolutePositionX = arguments[0];
  8801. absolutePositionY = arguments[1];
  8802. absolutePositionZ = arguments[2];
  8803. }
  8804. else {
  8805. absolutePositionX = absolutePosition.x;
  8806. absolutePositionY = absolutePosition.y;
  8807. absolutePositionZ = absolutePosition.z;
  8808. }
  8809. if (this.parent) {
  8810. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8811. invertParentWorldMatrix.invert();
  8812. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8813. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8814. }
  8815. else {
  8816. this.position.x = absolutePositionX;
  8817. this.position.y = absolutePositionY;
  8818. this.position.z = absolutePositionZ;
  8819. }
  8820. };
  8821. // ================================== Point of View Movement =================================
  8822. /**
  8823. * Perform relative position change from the point of view of behind the front of the mesh.
  8824. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8825. * Supports definition of mesh facing forward or backward.
  8826. * @param {number} amountRight
  8827. * @param {number} amountUp
  8828. * @param {number} amountForward
  8829. */
  8830. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8831. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8832. };
  8833. /**
  8834. * Calculate relative position change from the point of view of behind the front of the mesh.
  8835. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8836. * Supports definition of mesh facing forward or backward.
  8837. * @param {number} amountRight
  8838. * @param {number} amountUp
  8839. * @param {number} amountForward
  8840. */
  8841. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8842. var rotMatrix = new BABYLON.Matrix();
  8843. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8844. rotQuaternion.toRotationMatrix(rotMatrix);
  8845. var translationDelta = BABYLON.Vector3.Zero();
  8846. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8847. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8848. return translationDelta;
  8849. };
  8850. // ================================== Point of View Rotation =================================
  8851. /**
  8852. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8853. * Supports definition of mesh facing forward or backward.
  8854. * @param {number} flipBack
  8855. * @param {number} twirlClockwise
  8856. * @param {number} tiltRight
  8857. */
  8858. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8859. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8860. };
  8861. /**
  8862. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8863. * Supports definition of mesh facing forward or backward.
  8864. * @param {number} flipBack
  8865. * @param {number} twirlClockwise
  8866. * @param {number} tiltRight
  8867. */
  8868. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8869. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8870. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8871. };
  8872. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8873. this._pivotMatrix = matrix;
  8874. this._cache.pivotMatrixUpdated = true;
  8875. };
  8876. AbstractMesh.prototype.getPivotMatrix = function () {
  8877. return this._pivotMatrix;
  8878. };
  8879. AbstractMesh.prototype._isSynchronized = function () {
  8880. if (this._isDirty) {
  8881. return false;
  8882. }
  8883. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8884. return false;
  8885. if (this._cache.pivotMatrixUpdated) {
  8886. return false;
  8887. }
  8888. if (this.infiniteDistance) {
  8889. return false;
  8890. }
  8891. if (!this._cache.position.equals(this.position))
  8892. return false;
  8893. if (this.rotationQuaternion) {
  8894. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8895. return false;
  8896. }
  8897. else {
  8898. if (!this._cache.rotation.equals(this.rotation))
  8899. return false;
  8900. }
  8901. if (!this._cache.scaling.equals(this.scaling))
  8902. return false;
  8903. return true;
  8904. };
  8905. AbstractMesh.prototype._initCache = function () {
  8906. _super.prototype._initCache.call(this);
  8907. this._cache.localMatrixUpdated = false;
  8908. this._cache.position = BABYLON.Vector3.Zero();
  8909. this._cache.scaling = BABYLON.Vector3.Zero();
  8910. this._cache.rotation = BABYLON.Vector3.Zero();
  8911. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8912. this._cache.billboardMode = -1;
  8913. };
  8914. AbstractMesh.prototype.markAsDirty = function (property) {
  8915. if (property === "rotation") {
  8916. this.rotationQuaternion = null;
  8917. }
  8918. this._currentRenderId = Number.MAX_VALUE;
  8919. this._isDirty = true;
  8920. };
  8921. AbstractMesh.prototype._updateBoundingInfo = function () {
  8922. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8923. this._boundingInfo.update(this.worldMatrixFromCache);
  8924. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8925. };
  8926. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8927. if (!this.subMeshes) {
  8928. return;
  8929. }
  8930. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8931. var subMesh = this.subMeshes[subIndex];
  8932. if (!subMesh.IsGlobal) {
  8933. subMesh.updateBoundingInfo(matrix);
  8934. }
  8935. }
  8936. };
  8937. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8938. if (this._isWorldMatrixFrozen) {
  8939. return this._worldMatrix;
  8940. }
  8941. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8942. this._currentRenderId = this.getScene().getRenderId();
  8943. return this._worldMatrix;
  8944. }
  8945. this._cache.position.copyFrom(this.position);
  8946. this._cache.scaling.copyFrom(this.scaling);
  8947. this._cache.pivotMatrixUpdated = false;
  8948. this._cache.billboardMode = this.billboardMode;
  8949. this._currentRenderId = this.getScene().getRenderId();
  8950. this._isDirty = false;
  8951. // Scaling
  8952. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8953. // Rotation
  8954. //rotate, if quaternion is set and rotation was used
  8955. if (this.rotationQuaternion) {
  8956. var len = this.rotation.length();
  8957. if (len) {
  8958. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8959. this.rotation.copyFromFloats(0, 0, 0);
  8960. }
  8961. }
  8962. if (this.rotationQuaternion) {
  8963. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8964. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8965. }
  8966. else {
  8967. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8968. this._cache.rotation.copyFrom(this.rotation);
  8969. }
  8970. // Translation
  8971. if (this.infiniteDistance && !this.parent) {
  8972. var camera = this.getScene().activeCamera;
  8973. if (camera) {
  8974. var cameraWorldMatrix = camera.getWorldMatrix();
  8975. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8976. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8977. }
  8978. }
  8979. else {
  8980. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8981. }
  8982. // Composing transformations
  8983. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8984. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8985. // Billboarding
  8986. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8987. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8988. var localPosition = BABYLON.Tmp.Vector3[0];
  8989. if (this.parent && this.parent.getWorldMatrix) {
  8990. this._markSyncedWithParent();
  8991. var parentMatrix;
  8992. if (this._meshToBoneReferal) {
  8993. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8994. parentMatrix = BABYLON.Tmp.Matrix[6];
  8995. }
  8996. else {
  8997. parentMatrix = this.parent.getWorldMatrix();
  8998. }
  8999. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  9000. localPosition = BABYLON.Tmp.Vector3[1];
  9001. }
  9002. var zero = this.getScene().activeCamera.globalPosition.clone();
  9003. if (this.parent && this.parent.position) {
  9004. localPosition.addInPlace(this.parent.position);
  9005. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  9006. }
  9007. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  9008. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  9009. zero.x = localPosition.x + BABYLON.Epsilon;
  9010. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  9011. zero.y = localPosition.y + BABYLON.Epsilon;
  9012. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  9013. zero.z = localPosition.z + BABYLON.Epsilon;
  9014. }
  9015. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  9016. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  9017. BABYLON.Tmp.Matrix[3].invert();
  9018. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  9019. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  9020. }
  9021. // Local world
  9022. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  9023. // Parent
  9024. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  9025. this._markSyncedWithParent();
  9026. if (this._meshToBoneReferal) {
  9027. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  9028. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  9029. }
  9030. else {
  9031. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9032. }
  9033. }
  9034. else {
  9035. this._worldMatrix.copyFrom(this._localWorld);
  9036. }
  9037. // Bounding info
  9038. this._updateBoundingInfo();
  9039. // Absolute position
  9040. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9041. // Callbacks
  9042. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  9043. if (!this._poseMatrix) {
  9044. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  9045. }
  9046. return this._worldMatrix;
  9047. };
  9048. /**
  9049. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9050. * @param func: callback function to add
  9051. */
  9052. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9053. this.onAfterWorldMatrixUpdateObservable.add(func);
  9054. };
  9055. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9056. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  9057. };
  9058. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9059. this.computeWorldMatrix();
  9060. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9061. };
  9062. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9063. this.computeWorldMatrix();
  9064. var invLocalWorldMatrix = this._localWorld.clone();
  9065. invLocalWorldMatrix.invert();
  9066. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9067. };
  9068. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9069. this.computeWorldMatrix(true);
  9070. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9071. };
  9072. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9073. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9074. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  9075. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9076. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9077. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9078. /// <returns>Mesh oriented towards targetMesh</returns>
  9079. yawCor = yawCor || 0; // default to zero if undefined
  9080. pitchCor = pitchCor || 0;
  9081. rollCor = rollCor || 0;
  9082. var dv = targetPoint.subtract(this.position);
  9083. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9084. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9085. var pitch = Math.atan2(dv.y, len);
  9086. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9087. };
  9088. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9089. this._meshToBoneReferal = affectedMesh;
  9090. this.parent = bone;
  9091. if (bone.getWorldMatrix().determinant() < 0) {
  9092. this.scalingDeterminant *= -1;
  9093. }
  9094. };
  9095. AbstractMesh.prototype.detachFromBone = function () {
  9096. if (this.parent.getWorldMatrix().determinant() < 0) {
  9097. this.scalingDeterminant *= -1;
  9098. }
  9099. this._meshToBoneReferal = null;
  9100. this.parent = null;
  9101. };
  9102. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9103. return this._boundingInfo.isInFrustum(frustumPlanes);
  9104. };
  9105. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9106. if (!camera) {
  9107. camera = this.getScene().activeCamera;
  9108. }
  9109. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9110. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9111. return false;
  9112. }
  9113. return true;
  9114. };
  9115. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9116. if (!this._boundingInfo || !mesh._boundingInfo) {
  9117. return false;
  9118. }
  9119. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9120. };
  9121. AbstractMesh.prototype.intersectsPoint = function (point) {
  9122. if (!this._boundingInfo) {
  9123. return false;
  9124. }
  9125. return this._boundingInfo.intersectsPoint(point);
  9126. };
  9127. // Physics
  9128. /**
  9129. * @Deprecated. Use new PhysicsImpostor instead.
  9130. * */
  9131. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9132. //legacy support
  9133. if (impostor.impostor) {
  9134. options = impostor;
  9135. impostor = impostor.impostor;
  9136. }
  9137. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9138. return this.physicsImpostor.physicsBody;
  9139. };
  9140. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9141. return this.physicsImpostor;
  9142. };
  9143. /**
  9144. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9145. */
  9146. AbstractMesh.prototype.getPhysicsMass = function () {
  9147. return this.physicsImpostor.getParam("mass");
  9148. };
  9149. /**
  9150. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9151. */
  9152. AbstractMesh.prototype.getPhysicsFriction = function () {
  9153. return this.physicsImpostor.getParam("friction");
  9154. };
  9155. /**
  9156. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9157. */
  9158. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9159. return this.physicsImpostor.getParam("resitution");
  9160. };
  9161. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9162. if (!camera) {
  9163. camera = this.getScene().activeCamera;
  9164. }
  9165. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9166. };
  9167. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9168. if (!camera) {
  9169. camera = this.getScene().activeCamera;
  9170. }
  9171. return this.absolutePosition.subtract(camera.position).length();
  9172. };
  9173. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9174. if (!this.physicsImpostor) {
  9175. return;
  9176. }
  9177. this.physicsImpostor.applyImpulse(force, contactPoint);
  9178. };
  9179. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9180. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9181. return;
  9182. }
  9183. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9184. mainPivot: pivot1,
  9185. connectedPivot: pivot2,
  9186. nativeParams: options
  9187. });
  9188. };
  9189. /**
  9190. * @Deprecated
  9191. */
  9192. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9193. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9194. this.updatePhysicsBody();
  9195. };
  9196. /**
  9197. * @Deprecated
  9198. * Calling this function is not needed anymore.
  9199. * The physics engine takes care of transofmration automatically.
  9200. */
  9201. AbstractMesh.prototype.updatePhysicsBody = function () {
  9202. //Unneeded
  9203. };
  9204. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9205. // Collisions
  9206. get: function () {
  9207. return this._checkCollisions;
  9208. },
  9209. set: function (collisionEnabled) {
  9210. this._checkCollisions = collisionEnabled;
  9211. if (this.getScene().workerCollisions) {
  9212. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9213. }
  9214. },
  9215. enumerable: true,
  9216. configurable: true
  9217. });
  9218. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9219. var globalPosition = this.getAbsolutePosition();
  9220. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9221. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9222. this._collider.radius = this.ellipsoid;
  9223. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9224. };
  9225. // Submeshes octree
  9226. /**
  9227. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9228. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9229. */
  9230. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9231. if (maxCapacity === void 0) { maxCapacity = 64; }
  9232. if (maxDepth === void 0) { maxDepth = 2; }
  9233. if (!this._submeshesOctree) {
  9234. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9235. }
  9236. this.computeWorldMatrix(true);
  9237. // Update octree
  9238. var bbox = this.getBoundingInfo().boundingBox;
  9239. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9240. return this._submeshesOctree;
  9241. };
  9242. // Collisions
  9243. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9244. this._generatePointsArray();
  9245. // Transformation
  9246. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9247. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9248. subMesh._lastColliderWorldVertices = [];
  9249. subMesh._trianglePlanes = [];
  9250. var start = subMesh.verticesStart;
  9251. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9252. for (var i = start; i < end; i++) {
  9253. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9254. }
  9255. }
  9256. // Collide
  9257. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9258. if (collider.collisionFound) {
  9259. collider.collidedMesh = this;
  9260. }
  9261. };
  9262. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9263. var subMeshes;
  9264. var len;
  9265. // Octrees
  9266. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9267. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9268. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9269. len = intersections.length;
  9270. subMeshes = intersections.data;
  9271. }
  9272. else {
  9273. subMeshes = this.subMeshes;
  9274. len = subMeshes.length;
  9275. }
  9276. for (var index = 0; index < len; index++) {
  9277. var subMesh = subMeshes[index];
  9278. // Bounding test
  9279. if (len > 1 && !subMesh._checkCollision(collider))
  9280. continue;
  9281. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9282. }
  9283. };
  9284. AbstractMesh.prototype._checkCollision = function (collider) {
  9285. // Bounding box test
  9286. if (!this._boundingInfo._checkCollision(collider))
  9287. return;
  9288. // Transformation matrix
  9289. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9290. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9291. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9292. };
  9293. // Picking
  9294. AbstractMesh.prototype._generatePointsArray = function () {
  9295. return false;
  9296. };
  9297. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9298. var pickingInfo = new BABYLON.PickingInfo();
  9299. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9300. return pickingInfo;
  9301. }
  9302. if (!this._generatePointsArray()) {
  9303. return pickingInfo;
  9304. }
  9305. var intersectInfo = null;
  9306. // Octrees
  9307. var subMeshes;
  9308. var len;
  9309. if (this._submeshesOctree && this.useOctreeForPicking) {
  9310. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9311. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9312. len = intersections.length;
  9313. subMeshes = intersections.data;
  9314. }
  9315. else {
  9316. subMeshes = this.subMeshes;
  9317. len = subMeshes.length;
  9318. }
  9319. for (var index = 0; index < len; index++) {
  9320. var subMesh = subMeshes[index];
  9321. // Bounding test
  9322. if (len > 1 && !subMesh.canIntersects(ray))
  9323. continue;
  9324. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9325. if (currentIntersectInfo) {
  9326. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9327. intersectInfo = currentIntersectInfo;
  9328. intersectInfo.subMeshId = index;
  9329. if (fastCheck) {
  9330. break;
  9331. }
  9332. }
  9333. }
  9334. }
  9335. if (intersectInfo) {
  9336. // Get picked point
  9337. var world = this.getWorldMatrix();
  9338. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9339. var direction = ray.direction.clone();
  9340. direction = direction.scale(intersectInfo.distance);
  9341. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9342. var pickedPoint = worldOrigin.add(worldDirection);
  9343. // Return result
  9344. pickingInfo.hit = true;
  9345. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9346. pickingInfo.pickedPoint = pickedPoint;
  9347. pickingInfo.pickedMesh = this;
  9348. pickingInfo.bu = intersectInfo.bu;
  9349. pickingInfo.bv = intersectInfo.bv;
  9350. pickingInfo.faceId = intersectInfo.faceId;
  9351. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9352. return pickingInfo;
  9353. }
  9354. return pickingInfo;
  9355. };
  9356. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9357. return null;
  9358. };
  9359. AbstractMesh.prototype.releaseSubMeshes = function () {
  9360. if (this.subMeshes) {
  9361. while (this.subMeshes.length) {
  9362. this.subMeshes[0].dispose();
  9363. }
  9364. }
  9365. else {
  9366. this.subMeshes = new Array();
  9367. }
  9368. };
  9369. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9370. var _this = this;
  9371. var index;
  9372. // Action manager
  9373. if (this.actionManager) {
  9374. this.actionManager.dispose();
  9375. this.actionManager = null;
  9376. }
  9377. // Skeleton
  9378. this.skeleton = null;
  9379. // Animations
  9380. this.getScene().stopAnimation(this);
  9381. // Physics
  9382. if (this.physicsImpostor) {
  9383. this.physicsImpostor.dispose();
  9384. }
  9385. // Intersections in progress
  9386. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9387. var other = this._intersectionsInProgress[index];
  9388. var pos = other._intersectionsInProgress.indexOf(this);
  9389. other._intersectionsInProgress.splice(pos, 1);
  9390. }
  9391. this._intersectionsInProgress = [];
  9392. // Lights
  9393. var lights = this.getScene().lights;
  9394. lights.forEach(function (light) {
  9395. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9396. if (meshIndex !== -1) {
  9397. light.includedOnlyMeshes.splice(meshIndex, 1);
  9398. }
  9399. meshIndex = light.excludedMeshes.indexOf(_this);
  9400. if (meshIndex !== -1) {
  9401. light.excludedMeshes.splice(meshIndex, 1);
  9402. }
  9403. });
  9404. // Edges
  9405. if (this._edgesRenderer) {
  9406. this._edgesRenderer.dispose();
  9407. this._edgesRenderer = null;
  9408. }
  9409. // SubMeshes
  9410. this.releaseSubMeshes();
  9411. // Remove from scene
  9412. this.getScene().removeMesh(this);
  9413. if (!doNotRecurse) {
  9414. // Particles
  9415. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9416. if (this.getScene().particleSystems[index].emitter === this) {
  9417. this.getScene().particleSystems[index].dispose();
  9418. index--;
  9419. }
  9420. }
  9421. // Children
  9422. var objects = this.getDescendants(true);
  9423. for (index = 0; index < objects.length; index++) {
  9424. objects[index].dispose();
  9425. }
  9426. }
  9427. else {
  9428. var childMeshes = this.getChildMeshes(true);
  9429. for (index = 0; index < childMeshes.length; index++) {
  9430. var child = childMeshes[index];
  9431. child.parent = null;
  9432. child.computeWorldMatrix(true);
  9433. }
  9434. }
  9435. _super.prototype.dispose.call(this);
  9436. this.onAfterWorldMatrixUpdateObservable.clear();
  9437. this._isDisposed = true;
  9438. // Callback
  9439. if (this.onDispose) {
  9440. this.onDispose();
  9441. }
  9442. };
  9443. // Statics
  9444. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9445. AbstractMesh._BILLBOARDMODE_X = 1;
  9446. AbstractMesh._BILLBOARDMODE_Y = 2;
  9447. AbstractMesh._BILLBOARDMODE_Z = 4;
  9448. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9449. return AbstractMesh;
  9450. })(BABYLON.Node);
  9451. BABYLON.AbstractMesh = AbstractMesh;
  9452. })(BABYLON || (BABYLON = {}));
  9453. var BABYLON;
  9454. (function (BABYLON) {
  9455. var Light = (function (_super) {
  9456. __extends(Light, _super);
  9457. function Light(name, scene) {
  9458. _super.call(this, name, scene);
  9459. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9460. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9461. this.intensity = 1.0;
  9462. this.range = Number.MAX_VALUE;
  9463. this.includeOnlyWithLayerMask = 0;
  9464. this.includedOnlyMeshes = new Array();
  9465. this.excludedMeshes = new Array();
  9466. this.excludeWithLayerMask = 0;
  9467. // PBR Properties.
  9468. this.radius = 0.00001;
  9469. this._excludedMeshesIds = new Array();
  9470. this._includedOnlyMeshesIds = new Array();
  9471. scene.addLight(this);
  9472. }
  9473. /**
  9474. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9475. */
  9476. Light.prototype.toString = function (fullDetails) {
  9477. var ret = "Name: " + this.name;
  9478. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9479. if (this.animations) {
  9480. for (var i = 0; i < this.animations.length; i++) {
  9481. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9482. }
  9483. }
  9484. if (fullDetails) {
  9485. }
  9486. return ret;
  9487. };
  9488. Light.prototype.getShadowGenerator = function () {
  9489. return this._shadowGenerator;
  9490. };
  9491. Light.prototype.getAbsolutePosition = function () {
  9492. return BABYLON.Vector3.Zero();
  9493. };
  9494. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9495. };
  9496. Light.prototype._getWorldMatrix = function () {
  9497. return BABYLON.Matrix.Identity();
  9498. };
  9499. Light.prototype.canAffectMesh = function (mesh) {
  9500. if (!mesh) {
  9501. return true;
  9502. }
  9503. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9504. return false;
  9505. }
  9506. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9507. return false;
  9508. }
  9509. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9510. return false;
  9511. }
  9512. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9513. return false;
  9514. }
  9515. return true;
  9516. };
  9517. Light.prototype.getWorldMatrix = function () {
  9518. this._currentRenderId = this.getScene().getRenderId();
  9519. var worldMatrix = this._getWorldMatrix();
  9520. if (this.parent && this.parent.getWorldMatrix) {
  9521. if (!this._parentedWorldMatrix) {
  9522. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9523. }
  9524. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9525. this._markSyncedWithParent();
  9526. return this._parentedWorldMatrix;
  9527. }
  9528. return worldMatrix;
  9529. };
  9530. Light.prototype.dispose = function () {
  9531. if (this._shadowGenerator) {
  9532. this._shadowGenerator.dispose();
  9533. this._shadowGenerator = null;
  9534. }
  9535. // Animations
  9536. this.getScene().stopAnimation(this);
  9537. // Remove from scene
  9538. this.getScene().removeLight(this);
  9539. _super.prototype.dispose.call(this);
  9540. };
  9541. Light.prototype.getTypeID = function () {
  9542. return 0;
  9543. };
  9544. Light.prototype.clone = function (name) {
  9545. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9546. };
  9547. Light.prototype.serialize = function () {
  9548. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9549. // Type
  9550. serializationObject.type = this.getTypeID();
  9551. // Parent
  9552. if (this.parent) {
  9553. serializationObject.parentId = this.parent.id;
  9554. }
  9555. // Inclusion / exclusions
  9556. if (this.excludedMeshes.length > 0) {
  9557. serializationObject.excludedMeshesIds = [];
  9558. this.excludedMeshes.forEach(function (mesh) {
  9559. serializationObject.excludedMeshesIds.push(mesh.id);
  9560. });
  9561. }
  9562. if (this.includedOnlyMeshes.length > 0) {
  9563. serializationObject.includedOnlyMeshesIds = [];
  9564. this.includedOnlyMeshes.forEach(function (mesh) {
  9565. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9566. });
  9567. }
  9568. // Animations
  9569. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9570. serializationObject.ranges = this.serializeAnimationRanges();
  9571. return serializationObject;
  9572. };
  9573. Light.GetConstructorFromName = function (type, name, scene) {
  9574. switch (type) {
  9575. case 0:
  9576. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9577. case 1:
  9578. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9579. case 2:
  9580. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9581. case 3:
  9582. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9583. }
  9584. };
  9585. Light.Parse = function (parsedLight, scene) {
  9586. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9587. // Inclusion / exclusions
  9588. if (parsedLight.excludedMeshesIds) {
  9589. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9590. }
  9591. if (parsedLight.includedOnlyMeshesIds) {
  9592. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9593. }
  9594. // Parent
  9595. if (parsedLight.parentId) {
  9596. light._waitingParentId = parsedLight.parentId;
  9597. }
  9598. // Animations
  9599. if (parsedLight.animations) {
  9600. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9601. var parsedAnimation = parsedLight.animations[animationIndex];
  9602. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9603. }
  9604. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9605. }
  9606. if (parsedLight.autoAnimate) {
  9607. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9608. }
  9609. return light;
  9610. };
  9611. __decorate([
  9612. BABYLON.serializeAsColor3()
  9613. ], Light.prototype, "diffuse", void 0);
  9614. __decorate([
  9615. BABYLON.serializeAsColor3()
  9616. ], Light.prototype, "specular", void 0);
  9617. __decorate([
  9618. BABYLON.serialize()
  9619. ], Light.prototype, "intensity", void 0);
  9620. __decorate([
  9621. BABYLON.serialize()
  9622. ], Light.prototype, "range", void 0);
  9623. __decorate([
  9624. BABYLON.serialize()
  9625. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9626. __decorate([
  9627. BABYLON.serialize()
  9628. ], Light.prototype, "excludeWithLayerMask", void 0);
  9629. __decorate([
  9630. BABYLON.serialize()
  9631. ], Light.prototype, "radius", void 0);
  9632. return Light;
  9633. })(BABYLON.Node);
  9634. BABYLON.Light = Light;
  9635. })(BABYLON || (BABYLON = {}));
  9636. var BABYLON;
  9637. (function (BABYLON) {
  9638. var PointLight = (function (_super) {
  9639. __extends(PointLight, _super);
  9640. function PointLight(name, position, scene) {
  9641. _super.call(this, name, scene);
  9642. this.position = position;
  9643. }
  9644. PointLight.prototype.getAbsolutePosition = function () {
  9645. return this.transformedPosition ? this.transformedPosition : this.position;
  9646. };
  9647. PointLight.prototype.computeTransformedPosition = function () {
  9648. if (this.parent && this.parent.getWorldMatrix) {
  9649. if (!this.transformedPosition) {
  9650. this.transformedPosition = BABYLON.Vector3.Zero();
  9651. }
  9652. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9653. return true;
  9654. }
  9655. return false;
  9656. };
  9657. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9658. if (this.parent && this.parent.getWorldMatrix) {
  9659. this.computeTransformedPosition();
  9660. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9661. return;
  9662. }
  9663. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9664. };
  9665. PointLight.prototype.needCube = function () {
  9666. return true;
  9667. };
  9668. PointLight.prototype.supportsVSM = function () {
  9669. return false;
  9670. };
  9671. PointLight.prototype.needRefreshPerFrame = function () {
  9672. return false;
  9673. };
  9674. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9675. switch (faceIndex) {
  9676. case 0:
  9677. return new BABYLON.Vector3(1, 0, 0);
  9678. case 1:
  9679. return new BABYLON.Vector3(-1, 0, 0);
  9680. case 2:
  9681. return new BABYLON.Vector3(0, -1, 0);
  9682. case 3:
  9683. return new BABYLON.Vector3(0, 1, 0);
  9684. case 4:
  9685. return new BABYLON.Vector3(0, 0, 1);
  9686. case 5:
  9687. return new BABYLON.Vector3(0, 0, -1);
  9688. }
  9689. return BABYLON.Vector3.Zero();
  9690. };
  9691. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9692. var activeCamera = this.getScene().activeCamera;
  9693. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9694. };
  9695. PointLight.prototype._getWorldMatrix = function () {
  9696. if (!this._worldMatrix) {
  9697. this._worldMatrix = BABYLON.Matrix.Identity();
  9698. }
  9699. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9700. return this._worldMatrix;
  9701. };
  9702. PointLight.prototype.getTypeID = function () {
  9703. return 0;
  9704. };
  9705. __decorate([
  9706. BABYLON.serializeAsVector3()
  9707. ], PointLight.prototype, "position", void 0);
  9708. return PointLight;
  9709. })(BABYLON.Light);
  9710. BABYLON.PointLight = PointLight;
  9711. })(BABYLON || (BABYLON = {}));
  9712. var BABYLON;
  9713. (function (BABYLON) {
  9714. var SpotLight = (function (_super) {
  9715. __extends(SpotLight, _super);
  9716. function SpotLight(name, position, direction, angle, exponent, scene) {
  9717. _super.call(this, name, scene);
  9718. this.position = position;
  9719. this.direction = direction;
  9720. this.angle = angle;
  9721. this.exponent = exponent;
  9722. }
  9723. SpotLight.prototype.getAbsolutePosition = function () {
  9724. return this.transformedPosition ? this.transformedPosition : this.position;
  9725. };
  9726. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9727. var activeCamera = this.getScene().activeCamera;
  9728. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9729. };
  9730. SpotLight.prototype.needCube = function () {
  9731. return false;
  9732. };
  9733. SpotLight.prototype.supportsVSM = function () {
  9734. return true;
  9735. };
  9736. SpotLight.prototype.needRefreshPerFrame = function () {
  9737. return false;
  9738. };
  9739. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9740. return this.direction;
  9741. };
  9742. SpotLight.prototype.setDirectionToTarget = function (target) {
  9743. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9744. return this.direction;
  9745. };
  9746. SpotLight.prototype.computeTransformedPosition = function () {
  9747. if (this.parent && this.parent.getWorldMatrix) {
  9748. if (!this.transformedPosition) {
  9749. this.transformedPosition = BABYLON.Vector3.Zero();
  9750. }
  9751. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9752. return true;
  9753. }
  9754. return false;
  9755. };
  9756. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9757. var normalizeDirection;
  9758. if (this.parent && this.parent.getWorldMatrix) {
  9759. if (!this._transformedDirection) {
  9760. this._transformedDirection = BABYLON.Vector3.Zero();
  9761. }
  9762. this.computeTransformedPosition();
  9763. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9764. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9765. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9766. }
  9767. else {
  9768. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9769. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9770. }
  9771. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9772. };
  9773. SpotLight.prototype._getWorldMatrix = function () {
  9774. if (!this._worldMatrix) {
  9775. this._worldMatrix = BABYLON.Matrix.Identity();
  9776. }
  9777. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9778. return this._worldMatrix;
  9779. };
  9780. SpotLight.prototype.getTypeID = function () {
  9781. return 2;
  9782. };
  9783. __decorate([
  9784. BABYLON.serializeAsVector3()
  9785. ], SpotLight.prototype, "position", void 0);
  9786. __decorate([
  9787. BABYLON.serializeAsVector3()
  9788. ], SpotLight.prototype, "direction", void 0);
  9789. __decorate([
  9790. BABYLON.serialize()
  9791. ], SpotLight.prototype, "angle", void 0);
  9792. __decorate([
  9793. BABYLON.serialize()
  9794. ], SpotLight.prototype, "exponent", void 0);
  9795. return SpotLight;
  9796. })(BABYLON.Light);
  9797. BABYLON.SpotLight = SpotLight;
  9798. })(BABYLON || (BABYLON = {}));
  9799. var BABYLON;
  9800. (function (BABYLON) {
  9801. var HemisphericLight = (function (_super) {
  9802. __extends(HemisphericLight, _super);
  9803. function HemisphericLight(name, direction, scene) {
  9804. _super.call(this, name, scene);
  9805. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9806. this.direction = direction;
  9807. }
  9808. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9809. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9810. return this.direction;
  9811. };
  9812. HemisphericLight.prototype.getShadowGenerator = function () {
  9813. return null;
  9814. };
  9815. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9816. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9817. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9818. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9819. };
  9820. HemisphericLight.prototype._getWorldMatrix = function () {
  9821. if (!this._worldMatrix) {
  9822. this._worldMatrix = BABYLON.Matrix.Identity();
  9823. }
  9824. return this._worldMatrix;
  9825. };
  9826. HemisphericLight.prototype.getTypeID = function () {
  9827. return 3;
  9828. };
  9829. __decorate([
  9830. BABYLON.serializeAsColor3()
  9831. ], HemisphericLight.prototype, "groundColor", void 0);
  9832. __decorate([
  9833. BABYLON.serializeAsVector3()
  9834. ], HemisphericLight.prototype, "direction", void 0);
  9835. return HemisphericLight;
  9836. })(BABYLON.Light);
  9837. BABYLON.HemisphericLight = HemisphericLight;
  9838. })(BABYLON || (BABYLON = {}));
  9839. var BABYLON;
  9840. (function (BABYLON) {
  9841. var DirectionalLight = (function (_super) {
  9842. __extends(DirectionalLight, _super);
  9843. function DirectionalLight(name, direction, scene) {
  9844. _super.call(this, name, scene);
  9845. this.shadowOrthoScale = 0.5;
  9846. this.autoUpdateExtends = true;
  9847. // Cache
  9848. this._orthoLeft = Number.MAX_VALUE;
  9849. this._orthoRight = Number.MIN_VALUE;
  9850. this._orthoTop = Number.MIN_VALUE;
  9851. this._orthoBottom = Number.MAX_VALUE;
  9852. this.position = direction.scale(-1);
  9853. this.direction = direction;
  9854. }
  9855. DirectionalLight.prototype.getAbsolutePosition = function () {
  9856. return this.transformedPosition ? this.transformedPosition : this.position;
  9857. };
  9858. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9859. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9860. return this.direction;
  9861. };
  9862. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9863. var activeCamera = this.getScene().activeCamera;
  9864. // Check extends
  9865. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9866. var tempVector3 = BABYLON.Vector3.Zero();
  9867. this._orthoLeft = Number.MAX_VALUE;
  9868. this._orthoRight = Number.MIN_VALUE;
  9869. this._orthoTop = Number.MIN_VALUE;
  9870. this._orthoBottom = Number.MAX_VALUE;
  9871. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9872. var mesh = renderList[meshIndex];
  9873. if (!mesh) {
  9874. continue;
  9875. }
  9876. var boundingInfo = mesh.getBoundingInfo();
  9877. if (!boundingInfo) {
  9878. continue;
  9879. }
  9880. var boundingBox = boundingInfo.boundingBox;
  9881. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9882. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9883. if (tempVector3.x < this._orthoLeft)
  9884. this._orthoLeft = tempVector3.x;
  9885. if (tempVector3.y < this._orthoBottom)
  9886. this._orthoBottom = tempVector3.y;
  9887. if (tempVector3.x > this._orthoRight)
  9888. this._orthoRight = tempVector3.x;
  9889. if (tempVector3.y > this._orthoTop)
  9890. this._orthoTop = tempVector3.y;
  9891. }
  9892. }
  9893. }
  9894. var xOffset = this._orthoRight - this._orthoLeft;
  9895. var yOffset = this._orthoTop - this._orthoBottom;
  9896. 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);
  9897. };
  9898. DirectionalLight.prototype.supportsVSM = function () {
  9899. return true;
  9900. };
  9901. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9902. return true;
  9903. };
  9904. DirectionalLight.prototype.needCube = function () {
  9905. return false;
  9906. };
  9907. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9908. return this.direction;
  9909. };
  9910. DirectionalLight.prototype.computeTransformedPosition = function () {
  9911. if (this.parent && this.parent.getWorldMatrix) {
  9912. if (!this.transformedPosition) {
  9913. this.transformedPosition = BABYLON.Vector3.Zero();
  9914. }
  9915. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9916. return true;
  9917. }
  9918. return false;
  9919. };
  9920. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9921. if (this.parent && this.parent.getWorldMatrix) {
  9922. if (!this._transformedDirection) {
  9923. this._transformedDirection = BABYLON.Vector3.Zero();
  9924. }
  9925. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9926. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9927. return;
  9928. }
  9929. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9930. };
  9931. DirectionalLight.prototype._getWorldMatrix = function () {
  9932. if (!this._worldMatrix) {
  9933. this._worldMatrix = BABYLON.Matrix.Identity();
  9934. }
  9935. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9936. return this._worldMatrix;
  9937. };
  9938. DirectionalLight.prototype.getTypeID = function () {
  9939. return 1;
  9940. };
  9941. __decorate([
  9942. BABYLON.serializeAsVector3()
  9943. ], DirectionalLight.prototype, "position", void 0);
  9944. __decorate([
  9945. BABYLON.serializeAsVector3()
  9946. ], DirectionalLight.prototype, "direction", void 0);
  9947. __decorate([
  9948. BABYLON.serialize()
  9949. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9950. __decorate([
  9951. BABYLON.serialize()
  9952. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9953. return DirectionalLight;
  9954. })(BABYLON.Light);
  9955. BABYLON.DirectionalLight = DirectionalLight;
  9956. })(BABYLON || (BABYLON = {}));
  9957. var BABYLON;
  9958. (function (BABYLON) {
  9959. var ShadowGenerator = (function () {
  9960. function ShadowGenerator(mapSize, light) {
  9961. var _this = this;
  9962. // Members
  9963. this._filter = ShadowGenerator.FILTER_NONE;
  9964. this.blurScale = 2;
  9965. this._blurBoxOffset = 0;
  9966. this._bias = 0.00005;
  9967. this._lightDirection = BABYLON.Vector3.Zero();
  9968. this.forceBackFacesOnly = false;
  9969. this._darkness = 0;
  9970. this._transparencyShadow = false;
  9971. this._viewMatrix = BABYLON.Matrix.Zero();
  9972. this._projectionMatrix = BABYLON.Matrix.Zero();
  9973. this._transformMatrix = BABYLON.Matrix.Zero();
  9974. this._worldViewProjection = BABYLON.Matrix.Zero();
  9975. this._currentFaceIndex = 0;
  9976. this._currentFaceIndexCache = 0;
  9977. this._light = light;
  9978. this._scene = light.getScene();
  9979. this._mapSize = mapSize;
  9980. light._shadowGenerator = this;
  9981. // Render target
  9982. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9983. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9984. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9985. this._shadowMap.anisotropicFilteringLevel = 1;
  9986. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9987. this._shadowMap.renderParticles = false;
  9988. this._shadowMap.onBeforeRender = function (faceIndex) {
  9989. _this._currentFaceIndex = faceIndex;
  9990. };
  9991. this._shadowMap.onAfterUnbind = function () {
  9992. if (!_this.useBlurVarianceShadowMap) {
  9993. return;
  9994. }
  9995. if (!_this._shadowMap2) {
  9996. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9997. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9998. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9999. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  10000. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  10001. _this._downSamplePostprocess.onApply = function (effect) {
  10002. effect.setTexture("textureSampler", _this._shadowMap);
  10003. };
  10004. _this.blurBoxOffset = 1;
  10005. }
  10006. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  10007. };
  10008. // Custom render function
  10009. var renderSubMesh = function (subMesh) {
  10010. var mesh = subMesh.getRenderingMesh();
  10011. var scene = _this._scene;
  10012. var engine = scene.getEngine();
  10013. // Culling
  10014. engine.setState(subMesh.getMaterial().backFaceCulling);
  10015. // Managing instances
  10016. var batch = mesh._getInstancesRenderList(subMesh._id);
  10017. if (batch.mustReturn) {
  10018. return;
  10019. }
  10020. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10021. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  10022. engine.enableEffect(_this._effect);
  10023. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  10024. var material = subMesh.getMaterial();
  10025. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  10026. _this._effect.setVector3("lightPosition", _this.getLight().position);
  10027. if (_this.getLight().needCube()) {
  10028. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  10029. }
  10030. // Alpha test
  10031. if (material && material.needAlphaTesting()) {
  10032. var alphaTexture = material.getAlphaTestTexture();
  10033. _this._effect.setTexture("diffuseSampler", alphaTexture);
  10034. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  10035. }
  10036. // Bones
  10037. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10038. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  10039. }
  10040. if (_this.forceBackFacesOnly) {
  10041. engine.setState(true, 0, false, true);
  10042. }
  10043. // Draw
  10044. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  10045. if (_this.forceBackFacesOnly) {
  10046. engine.setState(true, 0, false, false);
  10047. }
  10048. }
  10049. else {
  10050. // Need to reset refresh rate of the shadowMap
  10051. _this._shadowMap.resetRefreshCounter();
  10052. }
  10053. };
  10054. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  10055. var index;
  10056. for (index = 0; index < opaqueSubMeshes.length; index++) {
  10057. renderSubMesh(opaqueSubMeshes.data[index]);
  10058. }
  10059. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  10060. renderSubMesh(alphaTestSubMeshes.data[index]);
  10061. }
  10062. if (_this._transparencyShadow) {
  10063. for (index = 0; index < transparentSubMeshes.length; index++) {
  10064. renderSubMesh(transparentSubMeshes.data[index]);
  10065. }
  10066. }
  10067. };
  10068. this._shadowMap.onClear = function (engine) {
  10069. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  10070. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  10071. }
  10072. else {
  10073. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  10074. }
  10075. };
  10076. }
  10077. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10078. // Static
  10079. get: function () {
  10080. return ShadowGenerator._FILTER_NONE;
  10081. },
  10082. enumerable: true,
  10083. configurable: true
  10084. });
  10085. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10086. get: function () {
  10087. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10088. },
  10089. enumerable: true,
  10090. configurable: true
  10091. });
  10092. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10093. get: function () {
  10094. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10095. },
  10096. enumerable: true,
  10097. configurable: true
  10098. });
  10099. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10100. get: function () {
  10101. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10102. },
  10103. enumerable: true,
  10104. configurable: true
  10105. });
  10106. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10107. get: function () {
  10108. return this._bias;
  10109. },
  10110. set: function (bias) {
  10111. this._bias = bias;
  10112. },
  10113. enumerable: true,
  10114. configurable: true
  10115. });
  10116. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10117. get: function () {
  10118. return this._blurBoxOffset;
  10119. },
  10120. set: function (value) {
  10121. var _this = this;
  10122. if (this._blurBoxOffset === value) {
  10123. return;
  10124. }
  10125. this._blurBoxOffset = value;
  10126. if (this._boxBlurPostprocess) {
  10127. this._boxBlurPostprocess.dispose();
  10128. }
  10129. 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);
  10130. this._boxBlurPostprocess.onApply = function (effect) {
  10131. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10132. };
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10138. get: function () {
  10139. return this._filter;
  10140. },
  10141. set: function (value) {
  10142. if (this._filter === value) {
  10143. return;
  10144. }
  10145. this._filter = value;
  10146. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10147. this._shadowMap.anisotropicFilteringLevel = 16;
  10148. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10149. }
  10150. else {
  10151. this._shadowMap.anisotropicFilteringLevel = 1;
  10152. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10153. }
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10159. get: function () {
  10160. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10161. },
  10162. set: function (value) {
  10163. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10169. get: function () {
  10170. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10171. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10172. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10173. },
  10174. set: function (value) {
  10175. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10176. },
  10177. enumerable: true,
  10178. configurable: true
  10179. });
  10180. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10181. get: function () {
  10182. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10183. },
  10184. set: function (value) {
  10185. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10186. },
  10187. enumerable: true,
  10188. configurable: true
  10189. });
  10190. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10191. var defines = [];
  10192. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10193. defines.push("#define VSM");
  10194. }
  10195. if (this.getLight().needCube()) {
  10196. defines.push("#define CUBEMAP");
  10197. }
  10198. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10199. var mesh = subMesh.getMesh();
  10200. var material = subMesh.getMaterial();
  10201. // Alpha test
  10202. if (material && material.needAlphaTesting()) {
  10203. defines.push("#define ALPHATEST");
  10204. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10205. attribs.push(BABYLON.VertexBuffer.UVKind);
  10206. defines.push("#define UV1");
  10207. }
  10208. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10209. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10210. defines.push("#define UV2");
  10211. }
  10212. }
  10213. // Bones
  10214. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10217. if (mesh.numBoneInfluencers > 4) {
  10218. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10219. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10220. }
  10221. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10222. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10223. }
  10224. else {
  10225. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10226. }
  10227. // Instances
  10228. if (useInstances) {
  10229. defines.push("#define INSTANCES");
  10230. attribs.push("world0");
  10231. attribs.push("world1");
  10232. attribs.push("world2");
  10233. attribs.push("world3");
  10234. }
  10235. // Get correct effect
  10236. var join = defines.join("\n");
  10237. if (this._cachedDefines !== join) {
  10238. this._cachedDefines = join;
  10239. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10240. }
  10241. return this._effect.isReady();
  10242. };
  10243. ShadowGenerator.prototype.getShadowMap = function () {
  10244. return this._shadowMap;
  10245. };
  10246. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10247. if (this._shadowMap2) {
  10248. return this._shadowMap2;
  10249. }
  10250. return this._shadowMap;
  10251. };
  10252. ShadowGenerator.prototype.getLight = function () {
  10253. return this._light;
  10254. };
  10255. // Methods
  10256. ShadowGenerator.prototype.getTransformMatrix = function () {
  10257. var scene = this._scene;
  10258. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10259. return this._transformMatrix;
  10260. }
  10261. this._currentRenderID = scene.getRenderId();
  10262. this._currentFaceIndexCache = this._currentFaceIndex;
  10263. var lightPosition = this._light.position;
  10264. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10265. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10266. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10267. }
  10268. if (this._light.computeTransformedPosition()) {
  10269. lightPosition = this._light.transformedPosition;
  10270. }
  10271. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10272. this._cachedPosition = lightPosition.clone();
  10273. this._cachedDirection = this._lightDirection.clone();
  10274. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10275. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10276. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10277. }
  10278. return this._transformMatrix;
  10279. };
  10280. ShadowGenerator.prototype.getDarkness = function () {
  10281. return this._darkness;
  10282. };
  10283. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10284. if (darkness >= 1.0)
  10285. this._darkness = 1.0;
  10286. else if (darkness <= 0.0)
  10287. this._darkness = 0.0;
  10288. else
  10289. this._darkness = darkness;
  10290. };
  10291. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10292. this._transparencyShadow = hasShadow;
  10293. };
  10294. ShadowGenerator.prototype._packHalf = function (depth) {
  10295. var scale = depth * 255.0;
  10296. var fract = scale - Math.floor(scale);
  10297. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10298. };
  10299. ShadowGenerator.prototype.dispose = function () {
  10300. this._shadowMap.dispose();
  10301. if (this._shadowMap2) {
  10302. this._shadowMap2.dispose();
  10303. }
  10304. if (this._downSamplePostprocess) {
  10305. this._downSamplePostprocess.dispose();
  10306. }
  10307. if (this._boxBlurPostprocess) {
  10308. this._boxBlurPostprocess.dispose();
  10309. }
  10310. };
  10311. ShadowGenerator.prototype.serialize = function () {
  10312. var serializationObject = {};
  10313. serializationObject.lightId = this._light.id;
  10314. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10315. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10316. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10317. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10318. serializationObject.renderList = [];
  10319. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10320. var mesh = this.getShadowMap().renderList[meshIndex];
  10321. serializationObject.renderList.push(mesh.id);
  10322. }
  10323. return serializationObject;
  10324. };
  10325. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10326. //casting to point light, as light is missing the position attr and typescript complains.
  10327. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10328. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10329. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10330. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  10331. meshes.forEach(function (mesh) {
  10332. shadowGenerator.getShadowMap().renderList.push(mesh);
  10333. });
  10334. }
  10335. if (parsedShadowGenerator.usePoissonSampling) {
  10336. shadowGenerator.usePoissonSampling = true;
  10337. }
  10338. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10339. shadowGenerator.useVarianceShadowMap = true;
  10340. }
  10341. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10342. shadowGenerator.useBlurVarianceShadowMap = true;
  10343. if (parsedShadowGenerator.blurScale) {
  10344. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10345. }
  10346. if (parsedShadowGenerator.blurBoxOffset) {
  10347. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10348. }
  10349. }
  10350. if (parsedShadowGenerator.bias !== undefined) {
  10351. shadowGenerator.bias = parsedShadowGenerator.bias;
  10352. }
  10353. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10354. return shadowGenerator;
  10355. };
  10356. ShadowGenerator._FILTER_NONE = 0;
  10357. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10358. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10359. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10360. return ShadowGenerator;
  10361. })();
  10362. BABYLON.ShadowGenerator = ShadowGenerator;
  10363. })(BABYLON || (BABYLON = {}));
  10364. var BABYLON;
  10365. (function (BABYLON) {
  10366. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10367. if (boxMin.x > sphereCenter.x + sphereRadius)
  10368. return false;
  10369. if (sphereCenter.x - sphereRadius > boxMax.x)
  10370. return false;
  10371. if (boxMin.y > sphereCenter.y + sphereRadius)
  10372. return false;
  10373. if (sphereCenter.y - sphereRadius > boxMax.y)
  10374. return false;
  10375. if (boxMin.z > sphereCenter.z + sphereRadius)
  10376. return false;
  10377. if (sphereCenter.z - sphereRadius > boxMax.z)
  10378. return false;
  10379. return true;
  10380. };
  10381. var getLowestRoot = function (a, b, c, maxR) {
  10382. var determinant = b * b - 4.0 * a * c;
  10383. var result = { root: 0, found: false };
  10384. if (determinant < 0)
  10385. return result;
  10386. var sqrtD = Math.sqrt(determinant);
  10387. var r1 = (-b - sqrtD) / (2.0 * a);
  10388. var r2 = (-b + sqrtD) / (2.0 * a);
  10389. if (r1 > r2) {
  10390. var temp = r2;
  10391. r2 = r1;
  10392. r1 = temp;
  10393. }
  10394. if (r1 > 0 && r1 < maxR) {
  10395. result.root = r1;
  10396. result.found = true;
  10397. return result;
  10398. }
  10399. if (r2 > 0 && r2 < maxR) {
  10400. result.root = r2;
  10401. result.found = true;
  10402. return result;
  10403. }
  10404. return result;
  10405. };
  10406. var Collider = (function () {
  10407. function Collider() {
  10408. this.radius = new BABYLON.Vector3(1, 1, 1);
  10409. this.retry = 0;
  10410. this.basePointWorld = BABYLON.Vector3.Zero();
  10411. this.velocityWorld = BABYLON.Vector3.Zero();
  10412. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10413. this._collisionPoint = BABYLON.Vector3.Zero();
  10414. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10415. this._tempVector = BABYLON.Vector3.Zero();
  10416. this._tempVector2 = BABYLON.Vector3.Zero();
  10417. this._tempVector3 = BABYLON.Vector3.Zero();
  10418. this._tempVector4 = BABYLON.Vector3.Zero();
  10419. this._edge = BABYLON.Vector3.Zero();
  10420. this._baseToVertex = BABYLON.Vector3.Zero();
  10421. this._destinationPoint = BABYLON.Vector3.Zero();
  10422. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10423. this._displacementVector = BABYLON.Vector3.Zero();
  10424. }
  10425. // Methods
  10426. Collider.prototype._initialize = function (source, dir, e) {
  10427. this.velocity = dir;
  10428. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10429. this.basePoint = source;
  10430. source.multiplyToRef(this.radius, this.basePointWorld);
  10431. dir.multiplyToRef(this.radius, this.velocityWorld);
  10432. this.velocityWorldLength = this.velocityWorld.length();
  10433. this.epsilon = e;
  10434. this.collisionFound = false;
  10435. };
  10436. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10437. pa.subtractToRef(point, this._tempVector);
  10438. pb.subtractToRef(point, this._tempVector2);
  10439. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10440. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10441. if (d < 0)
  10442. return false;
  10443. pc.subtractToRef(point, this._tempVector3);
  10444. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10445. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10446. if (d < 0)
  10447. return false;
  10448. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10449. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10450. return d >= 0;
  10451. };
  10452. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10453. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10454. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10455. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10456. return false;
  10457. }
  10458. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10459. return false;
  10460. return true;
  10461. };
  10462. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10463. var t0;
  10464. var embeddedInPlane = false;
  10465. //defensive programming, actually not needed.
  10466. if (!trianglePlaneArray) {
  10467. trianglePlaneArray = [];
  10468. }
  10469. if (!trianglePlaneArray[faceIndex]) {
  10470. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10471. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10472. }
  10473. var trianglePlane = trianglePlaneArray[faceIndex];
  10474. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10475. return;
  10476. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10477. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10478. if (normalDotVelocity == 0) {
  10479. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10480. return;
  10481. embeddedInPlane = true;
  10482. t0 = 0;
  10483. }
  10484. else {
  10485. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10486. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10487. if (t0 > t1) {
  10488. var temp = t1;
  10489. t1 = t0;
  10490. t0 = temp;
  10491. }
  10492. if (t0 > 1.0 || t1 < 0.0)
  10493. return;
  10494. if (t0 < 0)
  10495. t0 = 0;
  10496. if (t0 > 1.0)
  10497. t0 = 1.0;
  10498. }
  10499. this._collisionPoint.copyFromFloats(0, 0, 0);
  10500. var found = false;
  10501. var t = 1.0;
  10502. if (!embeddedInPlane) {
  10503. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10504. this.velocity.scaleToRef(t0, this._tempVector);
  10505. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10506. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10507. found = true;
  10508. t = t0;
  10509. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10510. }
  10511. }
  10512. if (!found) {
  10513. var velocitySquaredLength = this.velocity.lengthSquared();
  10514. var a = velocitySquaredLength;
  10515. this.basePoint.subtractToRef(p1, this._tempVector);
  10516. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10517. var c = this._tempVector.lengthSquared() - 1.0;
  10518. var lowestRoot = getLowestRoot(a, b, c, t);
  10519. if (lowestRoot.found) {
  10520. t = lowestRoot.root;
  10521. found = true;
  10522. this._collisionPoint.copyFrom(p1);
  10523. }
  10524. this.basePoint.subtractToRef(p2, this._tempVector);
  10525. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10526. c = this._tempVector.lengthSquared() - 1.0;
  10527. lowestRoot = getLowestRoot(a, b, c, t);
  10528. if (lowestRoot.found) {
  10529. t = lowestRoot.root;
  10530. found = true;
  10531. this._collisionPoint.copyFrom(p2);
  10532. }
  10533. this.basePoint.subtractToRef(p3, this._tempVector);
  10534. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10535. c = this._tempVector.lengthSquared() - 1.0;
  10536. lowestRoot = getLowestRoot(a, b, c, t);
  10537. if (lowestRoot.found) {
  10538. t = lowestRoot.root;
  10539. found = true;
  10540. this._collisionPoint.copyFrom(p3);
  10541. }
  10542. p2.subtractToRef(p1, this._edge);
  10543. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10544. var edgeSquaredLength = this._edge.lengthSquared();
  10545. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10546. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10547. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10548. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10549. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10550. lowestRoot = getLowestRoot(a, b, c, t);
  10551. if (lowestRoot.found) {
  10552. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10553. if (f >= 0.0 && f <= 1.0) {
  10554. t = lowestRoot.root;
  10555. found = true;
  10556. this._edge.scaleInPlace(f);
  10557. p1.addToRef(this._edge, this._collisionPoint);
  10558. }
  10559. }
  10560. p3.subtractToRef(p2, this._edge);
  10561. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10562. edgeSquaredLength = this._edge.lengthSquared();
  10563. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10564. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10565. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10566. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10567. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10568. lowestRoot = getLowestRoot(a, b, c, t);
  10569. if (lowestRoot.found) {
  10570. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10571. if (f >= 0.0 && f <= 1.0) {
  10572. t = lowestRoot.root;
  10573. found = true;
  10574. this._edge.scaleInPlace(f);
  10575. p2.addToRef(this._edge, this._collisionPoint);
  10576. }
  10577. }
  10578. p1.subtractToRef(p3, this._edge);
  10579. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10580. edgeSquaredLength = this._edge.lengthSquared();
  10581. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10582. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10583. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10584. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10585. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10586. lowestRoot = getLowestRoot(a, b, c, t);
  10587. if (lowestRoot.found) {
  10588. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10589. if (f >= 0.0 && f <= 1.0) {
  10590. t = lowestRoot.root;
  10591. found = true;
  10592. this._edge.scaleInPlace(f);
  10593. p3.addToRef(this._edge, this._collisionPoint);
  10594. }
  10595. }
  10596. }
  10597. if (found) {
  10598. var distToCollision = t * this.velocity.length();
  10599. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10600. if (!this.intersectionPoint) {
  10601. this.intersectionPoint = this._collisionPoint.clone();
  10602. }
  10603. else {
  10604. this.intersectionPoint.copyFrom(this._collisionPoint);
  10605. }
  10606. this.nearestDistance = distToCollision;
  10607. this.collisionFound = true;
  10608. }
  10609. }
  10610. };
  10611. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10612. for (var i = indexStart; i < indexEnd; i += 3) {
  10613. var p1 = pts[indices[i] - decal];
  10614. var p2 = pts[indices[i + 1] - decal];
  10615. var p3 = pts[indices[i + 2] - decal];
  10616. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10617. }
  10618. };
  10619. Collider.prototype._getResponse = function (pos, vel) {
  10620. pos.addToRef(vel, this._destinationPoint);
  10621. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10622. this.basePoint.addToRef(vel, pos);
  10623. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10624. this._slidePlaneNormal.normalize();
  10625. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10626. pos.addInPlace(this._displacementVector);
  10627. this.intersectionPoint.addInPlace(this._displacementVector);
  10628. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10629. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10630. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10631. };
  10632. return Collider;
  10633. })();
  10634. BABYLON.Collider = Collider;
  10635. })(BABYLON || (BABYLON = {}));
  10636. var BABYLON;
  10637. (function (BABYLON) {
  10638. //WebWorker code will be inserted to this variable.
  10639. BABYLON.CollisionWorker = "";
  10640. (function (WorkerTaskType) {
  10641. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10642. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10643. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10644. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10645. var WorkerTaskType = BABYLON.WorkerTaskType;
  10646. (function (WorkerReplyType) {
  10647. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10648. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10649. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10650. var WorkerReplyType = BABYLON.WorkerReplyType;
  10651. var CollisionCoordinatorWorker = (function () {
  10652. function CollisionCoordinatorWorker() {
  10653. var _this = this;
  10654. this._scaledPosition = BABYLON.Vector3.Zero();
  10655. this._scaledVelocity = BABYLON.Vector3.Zero();
  10656. this.onMeshUpdated = function (mesh) {
  10657. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10658. };
  10659. this.onGeometryUpdated = function (geometry) {
  10660. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10661. };
  10662. this._afterRender = function () {
  10663. if (!_this._init)
  10664. return;
  10665. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10666. return;
  10667. }
  10668. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10669. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10670. if (_this._runningUpdated > 4) {
  10671. return;
  10672. }
  10673. ++_this._runningUpdated;
  10674. var payload = {
  10675. updatedMeshes: _this._addUpdateMeshesList,
  10676. updatedGeometries: _this._addUpdateGeometriesList,
  10677. removedGeometries: _this._toRemoveGeometryArray,
  10678. removedMeshes: _this._toRemoveMeshesArray
  10679. };
  10680. var message = {
  10681. payload: payload,
  10682. taskType: WorkerTaskType.UPDATE
  10683. };
  10684. var serializable = [];
  10685. for (var id in payload.updatedGeometries) {
  10686. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10687. //prepare transferables
  10688. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10689. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10690. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10691. }
  10692. }
  10693. _this._worker.postMessage(message, serializable);
  10694. _this._addUpdateMeshesList = {};
  10695. _this._addUpdateGeometriesList = {};
  10696. _this._toRemoveGeometryArray = [];
  10697. _this._toRemoveMeshesArray = [];
  10698. };
  10699. this._onMessageFromWorker = function (e) {
  10700. var returnData = e.data;
  10701. if (returnData.error != WorkerReplyType.SUCCESS) {
  10702. //TODO what errors can be returned from the worker?
  10703. BABYLON.Tools.Warn("error returned from worker!");
  10704. return;
  10705. }
  10706. switch (returnData.taskType) {
  10707. case WorkerTaskType.INIT:
  10708. _this._init = true;
  10709. //Update the worked with ALL of the scene's current state
  10710. _this._scene.meshes.forEach(function (mesh) {
  10711. _this.onMeshAdded(mesh);
  10712. });
  10713. _this._scene.getGeometries().forEach(function (geometry) {
  10714. _this.onGeometryAdded(geometry);
  10715. });
  10716. break;
  10717. case WorkerTaskType.UPDATE:
  10718. _this._runningUpdated--;
  10719. break;
  10720. case WorkerTaskType.COLLIDE:
  10721. _this._runningCollisionTask = false;
  10722. var returnPayload = returnData.payload;
  10723. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10724. return;
  10725. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10726. //cleanup
  10727. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10728. break;
  10729. }
  10730. };
  10731. this._collisionsCallbackArray = [];
  10732. this._init = false;
  10733. this._runningUpdated = 0;
  10734. this._runningCollisionTask = false;
  10735. this._addUpdateMeshesList = {};
  10736. this._addUpdateGeometriesList = {};
  10737. this._toRemoveGeometryArray = [];
  10738. this._toRemoveMeshesArray = [];
  10739. }
  10740. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10741. if (!this._init)
  10742. return;
  10743. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10744. return;
  10745. position.divideToRef(collider.radius, this._scaledPosition);
  10746. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10747. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10748. var payload = {
  10749. collider: {
  10750. position: this._scaledPosition.asArray(),
  10751. velocity: this._scaledVelocity.asArray(),
  10752. radius: collider.radius.asArray()
  10753. },
  10754. collisionId: collisionIndex,
  10755. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10756. maximumRetry: maximumRetry
  10757. };
  10758. var message = {
  10759. payload: payload,
  10760. taskType: WorkerTaskType.COLLIDE
  10761. };
  10762. this._worker.postMessage(message);
  10763. };
  10764. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10765. this._scene = scene;
  10766. this._scene.registerAfterRender(this._afterRender);
  10767. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10768. this._worker = new Worker(workerUrl);
  10769. this._worker.onmessage = this._onMessageFromWorker;
  10770. var message = {
  10771. payload: {},
  10772. taskType: WorkerTaskType.INIT
  10773. };
  10774. this._worker.postMessage(message);
  10775. };
  10776. CollisionCoordinatorWorker.prototype.destroy = function () {
  10777. this._scene.unregisterAfterRender(this._afterRender);
  10778. this._worker.terminate();
  10779. };
  10780. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10781. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10782. this.onMeshUpdated(mesh);
  10783. };
  10784. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10785. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10786. };
  10787. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10788. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10789. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10790. this.onGeometryUpdated(geometry);
  10791. };
  10792. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10793. this._toRemoveGeometryArray.push(geometry.id);
  10794. };
  10795. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10796. var submeshes = [];
  10797. if (mesh.subMeshes) {
  10798. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10799. return {
  10800. position: idx,
  10801. verticesStart: sm.verticesStart,
  10802. verticesCount: sm.verticesCount,
  10803. indexStart: sm.indexStart,
  10804. indexCount: sm.indexCount,
  10805. hasMaterial: !!sm.getMaterial(),
  10806. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10807. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10808. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10809. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10810. };
  10811. });
  10812. }
  10813. var geometryId = null;
  10814. if (mesh instanceof BABYLON.Mesh) {
  10815. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10816. }
  10817. else if (mesh instanceof BABYLON.InstancedMesh) {
  10818. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10819. }
  10820. return {
  10821. uniqueId: mesh.uniqueId,
  10822. id: mesh.id,
  10823. name: mesh.name,
  10824. geometryId: geometryId,
  10825. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10826. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10827. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10828. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10829. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10830. subMeshes: submeshes,
  10831. checkCollisions: mesh.checkCollisions
  10832. };
  10833. };
  10834. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10835. return {
  10836. id: geometry.id,
  10837. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10838. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10839. indices: new Int32Array(geometry.getIndices() || []),
  10840. };
  10841. };
  10842. return CollisionCoordinatorWorker;
  10843. })();
  10844. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10845. var CollisionCoordinatorLegacy = (function () {
  10846. function CollisionCoordinatorLegacy() {
  10847. this._scaledPosition = BABYLON.Vector3.Zero();
  10848. this._scaledVelocity = BABYLON.Vector3.Zero();
  10849. this._finalPosition = BABYLON.Vector3.Zero();
  10850. }
  10851. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10852. position.divideToRef(collider.radius, this._scaledPosition);
  10853. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10854. collider.collidedMesh = null;
  10855. collider.retry = 0;
  10856. collider.initialVelocity = this._scaledVelocity;
  10857. collider.initialPosition = this._scaledPosition;
  10858. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10859. this._finalPosition.multiplyInPlace(collider.radius);
  10860. //run the callback
  10861. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10862. };
  10863. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10864. this._scene = scene;
  10865. };
  10866. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10867. //Legacy need no destruction method.
  10868. };
  10869. //No update in legacy mode
  10870. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10871. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10872. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10873. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10874. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10875. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10876. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10877. if (excludedMesh === void 0) { excludedMesh = null; }
  10878. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10879. if (collider.retry >= maximumRetry) {
  10880. finalPosition.copyFrom(position);
  10881. return;
  10882. }
  10883. collider._initialize(position, velocity, closeDistance);
  10884. // Check all meshes
  10885. for (var index = 0; index < this._scene.meshes.length; index++) {
  10886. var mesh = this._scene.meshes[index];
  10887. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10888. mesh._checkCollision(collider);
  10889. }
  10890. }
  10891. if (!collider.collisionFound) {
  10892. position.addToRef(velocity, finalPosition);
  10893. return;
  10894. }
  10895. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10896. collider._getResponse(position, velocity);
  10897. }
  10898. if (velocity.length() <= closeDistance) {
  10899. finalPosition.copyFrom(position);
  10900. return;
  10901. }
  10902. collider.retry++;
  10903. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10904. };
  10905. return CollisionCoordinatorLegacy;
  10906. })();
  10907. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10908. })(BABYLON || (BABYLON = {}));
  10909. var BABYLON;
  10910. (function (BABYLON) {
  10911. var Camera = (function (_super) {
  10912. __extends(Camera, _super);
  10913. function Camera(name, position, scene) {
  10914. _super.call(this, name, scene);
  10915. this.upVector = BABYLON.Vector3.Up();
  10916. this.orthoLeft = null;
  10917. this.orthoRight = null;
  10918. this.orthoBottom = null;
  10919. this.orthoTop = null;
  10920. this.fov = 0.8;
  10921. this.minZ = 1.0;
  10922. this.maxZ = 10000.0;
  10923. this.inertia = 0.9;
  10924. this.mode = Camera.PERSPECTIVE_CAMERA;
  10925. this.isIntermediate = false;
  10926. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10927. this.layerMask = 0x0FFFFFFF;
  10928. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10929. // Camera rig members
  10930. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10931. this._rigCameras = new Array();
  10932. // Cache
  10933. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10934. this._projectionMatrix = new BABYLON.Matrix();
  10935. this._postProcesses = new Array();
  10936. this._postProcessesTakenIndices = [];
  10937. this._activeMeshes = new BABYLON.SmartArray(256);
  10938. this._globalPosition = BABYLON.Vector3.Zero();
  10939. scene.addCamera(this);
  10940. if (!scene.activeCamera) {
  10941. scene.activeCamera = this;
  10942. }
  10943. this.position = position;
  10944. }
  10945. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10946. get: function () {
  10947. return Camera._PERSPECTIVE_CAMERA;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10953. get: function () {
  10954. return Camera._ORTHOGRAPHIC_CAMERA;
  10955. },
  10956. enumerable: true,
  10957. configurable: true
  10958. });
  10959. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10960. get: function () {
  10961. return Camera._FOVMODE_VERTICAL_FIXED;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10967. get: function () {
  10968. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10969. },
  10970. enumerable: true,
  10971. configurable: true
  10972. });
  10973. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10974. get: function () {
  10975. return Camera._RIG_MODE_NONE;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10981. get: function () {
  10982. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10988. get: function () {
  10989. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10995. get: function () {
  10996. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  11002. get: function () {
  11003. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(Camera, "RIG_MODE_VR", {
  11009. get: function () {
  11010. return Camera._RIG_MODE_VR;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. /**
  11016. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11017. */
  11018. Camera.prototype.toString = function (fullDetails) {
  11019. var ret = "Name: " + this.name;
  11020. ret += ", type: " + this.getTypeName();
  11021. if (this.animations) {
  11022. for (var i = 0; i < this.animations.length; i++) {
  11023. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11024. }
  11025. }
  11026. if (fullDetails) {
  11027. }
  11028. return ret;
  11029. };
  11030. Object.defineProperty(Camera.prototype, "globalPosition", {
  11031. get: function () {
  11032. return this._globalPosition;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. Camera.prototype.getActiveMeshes = function () {
  11038. return this._activeMeshes;
  11039. };
  11040. Camera.prototype.isActiveMesh = function (mesh) {
  11041. return (this._activeMeshes.indexOf(mesh) !== -1);
  11042. };
  11043. //Cache
  11044. Camera.prototype._initCache = function () {
  11045. _super.prototype._initCache.call(this);
  11046. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11047. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11048. this._cache.mode = undefined;
  11049. this._cache.minZ = undefined;
  11050. this._cache.maxZ = undefined;
  11051. this._cache.fov = undefined;
  11052. this._cache.aspectRatio = undefined;
  11053. this._cache.orthoLeft = undefined;
  11054. this._cache.orthoRight = undefined;
  11055. this._cache.orthoBottom = undefined;
  11056. this._cache.orthoTop = undefined;
  11057. this._cache.renderWidth = undefined;
  11058. this._cache.renderHeight = undefined;
  11059. };
  11060. Camera.prototype._updateCache = function (ignoreParentClass) {
  11061. if (!ignoreParentClass) {
  11062. _super.prototype._updateCache.call(this);
  11063. }
  11064. var engine = this.getEngine();
  11065. this._cache.position.copyFrom(this.position);
  11066. this._cache.upVector.copyFrom(this.upVector);
  11067. this._cache.mode = this.mode;
  11068. this._cache.minZ = this.minZ;
  11069. this._cache.maxZ = this.maxZ;
  11070. this._cache.fov = this.fov;
  11071. this._cache.aspectRatio = engine.getAspectRatio(this);
  11072. this._cache.orthoLeft = this.orthoLeft;
  11073. this._cache.orthoRight = this.orthoRight;
  11074. this._cache.orthoBottom = this.orthoBottom;
  11075. this._cache.orthoTop = this.orthoTop;
  11076. this._cache.renderWidth = engine.getRenderWidth();
  11077. this._cache.renderHeight = engine.getRenderHeight();
  11078. };
  11079. Camera.prototype._updateFromScene = function () {
  11080. this.updateCache();
  11081. this._update();
  11082. };
  11083. // Synchronized
  11084. Camera.prototype._isSynchronized = function () {
  11085. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11086. };
  11087. Camera.prototype._isSynchronizedViewMatrix = function () {
  11088. if (!_super.prototype._isSynchronized.call(this))
  11089. return false;
  11090. return this._cache.position.equals(this.position)
  11091. && this._cache.upVector.equals(this.upVector)
  11092. && this.isSynchronizedWithParent();
  11093. };
  11094. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11095. var check = this._cache.mode === this.mode
  11096. && this._cache.minZ === this.minZ
  11097. && this._cache.maxZ === this.maxZ;
  11098. if (!check) {
  11099. return false;
  11100. }
  11101. var engine = this.getEngine();
  11102. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11103. check = this._cache.fov === this.fov
  11104. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11105. }
  11106. else {
  11107. check = this._cache.orthoLeft === this.orthoLeft
  11108. && this._cache.orthoRight === this.orthoRight
  11109. && this._cache.orthoBottom === this.orthoBottom
  11110. && this._cache.orthoTop === this.orthoTop
  11111. && this._cache.renderWidth === engine.getRenderWidth()
  11112. && this._cache.renderHeight === engine.getRenderHeight();
  11113. }
  11114. return check;
  11115. };
  11116. // Controls
  11117. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11118. };
  11119. Camera.prototype.detachControl = function (element) {
  11120. };
  11121. Camera.prototype._update = function () {
  11122. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11123. this._updateRigCameras();
  11124. }
  11125. this._checkInputs();
  11126. };
  11127. Camera.prototype._checkInputs = function () {
  11128. };
  11129. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11130. if (insertAt === void 0) { insertAt = null; }
  11131. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11132. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11133. return 0;
  11134. }
  11135. if (insertAt == null || insertAt < 0) {
  11136. this._postProcesses.push(postProcess);
  11137. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11138. return this._postProcesses.length - 1;
  11139. }
  11140. var add = 0;
  11141. var i;
  11142. var start;
  11143. if (this._postProcesses[insertAt]) {
  11144. start = this._postProcesses.length - 1;
  11145. for (i = start; i >= insertAt + 1; --i) {
  11146. this._postProcesses[i + 1] = this._postProcesses[i];
  11147. }
  11148. add = 1;
  11149. }
  11150. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11151. if (this._postProcessesTakenIndices[i] < insertAt) {
  11152. continue;
  11153. }
  11154. start = this._postProcessesTakenIndices.length - 1;
  11155. for (var j = start; j >= i; --j) {
  11156. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11157. }
  11158. this._postProcessesTakenIndices[i] = insertAt;
  11159. break;
  11160. }
  11161. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11162. this._postProcessesTakenIndices.push(insertAt);
  11163. }
  11164. var result = insertAt + add;
  11165. this._postProcesses[result] = postProcess;
  11166. return result;
  11167. };
  11168. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11169. if (atIndices === void 0) { atIndices = null; }
  11170. var result = [];
  11171. var i;
  11172. var index;
  11173. if (!atIndices) {
  11174. var length = this._postProcesses.length;
  11175. for (i = 0; i < length; i++) {
  11176. if (this._postProcesses[i] !== postProcess) {
  11177. continue;
  11178. }
  11179. delete this._postProcesses[i];
  11180. index = this._postProcessesTakenIndices.indexOf(i);
  11181. this._postProcessesTakenIndices.splice(index, 1);
  11182. }
  11183. }
  11184. else {
  11185. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11186. for (i = 0; i < atIndices.length; i++) {
  11187. var foundPostProcess = this._postProcesses[atIndices[i]];
  11188. if (foundPostProcess !== postProcess) {
  11189. result.push(i);
  11190. continue;
  11191. }
  11192. delete this._postProcesses[atIndices[i]];
  11193. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11194. this._postProcessesTakenIndices.splice(index, 1);
  11195. }
  11196. }
  11197. return result;
  11198. };
  11199. Camera.prototype.getWorldMatrix = function () {
  11200. if (!this._worldMatrix) {
  11201. this._worldMatrix = BABYLON.Matrix.Identity();
  11202. }
  11203. var viewMatrix = this.getViewMatrix();
  11204. viewMatrix.invertToRef(this._worldMatrix);
  11205. return this._worldMatrix;
  11206. };
  11207. Camera.prototype._getViewMatrix = function () {
  11208. return BABYLON.Matrix.Identity();
  11209. };
  11210. Camera.prototype.getViewMatrix = function (force) {
  11211. this._computedViewMatrix = this._computeViewMatrix(force);
  11212. if (!force && this._isSynchronizedViewMatrix()) {
  11213. return this._computedViewMatrix;
  11214. }
  11215. if (!this.parent || !this.parent.getWorldMatrix) {
  11216. this._globalPosition.copyFrom(this.position);
  11217. }
  11218. else {
  11219. if (!this._worldMatrix) {
  11220. this._worldMatrix = BABYLON.Matrix.Identity();
  11221. }
  11222. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11223. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11224. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11225. this._computedViewMatrix.invert();
  11226. this._markSyncedWithParent();
  11227. }
  11228. this._currentRenderId = this.getScene().getRenderId();
  11229. return this._computedViewMatrix;
  11230. };
  11231. Camera.prototype._computeViewMatrix = function (force) {
  11232. if (!force && this._isSynchronizedViewMatrix()) {
  11233. return this._computedViewMatrix;
  11234. }
  11235. this._computedViewMatrix = this._getViewMatrix();
  11236. this._currentRenderId = this.getScene().getRenderId();
  11237. return this._computedViewMatrix;
  11238. };
  11239. Camera.prototype.getProjectionMatrix = function (force) {
  11240. if (!force && this._isSynchronizedProjectionMatrix()) {
  11241. return this._projectionMatrix;
  11242. }
  11243. var engine = this.getEngine();
  11244. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11245. if (this.minZ <= 0) {
  11246. this.minZ = 0.1;
  11247. }
  11248. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11249. return this._projectionMatrix;
  11250. }
  11251. var halfWidth = engine.getRenderWidth() / 2.0;
  11252. var halfHeight = engine.getRenderHeight() / 2.0;
  11253. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11254. return this._projectionMatrix;
  11255. };
  11256. Camera.prototype.dispose = function () {
  11257. // Animations
  11258. this.getScene().stopAnimation(this);
  11259. // Remove from scene
  11260. this.getScene().removeCamera(this);
  11261. while (this._rigCameras.length > 0) {
  11262. this._rigCameras.pop().dispose();
  11263. }
  11264. // Postprocesses
  11265. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11266. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11267. }
  11268. _super.prototype.dispose.call(this);
  11269. };
  11270. // ---- Camera rigs section ----
  11271. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11272. while (this._rigCameras.length > 0) {
  11273. this._rigCameras.pop().dispose();
  11274. }
  11275. this.cameraRigMode = mode;
  11276. this._cameraRigParams = {};
  11277. switch (this.cameraRigMode) {
  11278. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11279. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11280. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11281. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11282. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11283. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11284. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11285. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11286. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11287. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11288. break;
  11289. }
  11290. var postProcesses = new Array();
  11291. switch (this.cameraRigMode) {
  11292. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11293. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11294. this._rigCameras[0].isIntermediate = true;
  11295. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11296. postProcesses[1].onApply = function (effect) {
  11297. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11298. };
  11299. break;
  11300. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11301. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11302. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11303. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11304. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11305. var secondCamIndex = 1 - firstCamIndex;
  11306. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11307. this._rigCameras[firstCamIndex].isIntermediate = true;
  11308. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11309. break;
  11310. case Camera.RIG_MODE_VR:
  11311. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11312. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11313. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11314. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11315. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11316. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11317. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11318. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11319. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11320. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11321. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11322. if (metrics.compensateDistortion) {
  11323. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11324. }
  11325. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11326. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11327. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11328. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11329. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11330. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11331. if (metrics.compensateDistortion) {
  11332. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11333. }
  11334. break;
  11335. }
  11336. this._update();
  11337. };
  11338. Camera.prototype._getVRProjectionMatrix = function () {
  11339. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11340. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11341. return this._projectionMatrix;
  11342. };
  11343. Camera.prototype.setCameraRigParameter = function (name, value) {
  11344. this._cameraRigParams[name] = value;
  11345. //provisionnally:
  11346. if (name === "interaxialDistance") {
  11347. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11348. }
  11349. };
  11350. /**
  11351. * May needs to be overridden by children so sub has required properties to be copied
  11352. */
  11353. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11354. return null;
  11355. };
  11356. /**
  11357. * May needs to be overridden by children
  11358. */
  11359. Camera.prototype._updateRigCameras = function () {
  11360. for (var i = 0; i < this._rigCameras.length; i++) {
  11361. this._rigCameras[i].minZ = this.minZ;
  11362. this._rigCameras[i].maxZ = this.maxZ;
  11363. this._rigCameras[i].fov = this.fov;
  11364. }
  11365. // only update viewport when ANAGLYPH
  11366. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11367. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11368. }
  11369. };
  11370. Camera.prototype._setupInputs = function () {
  11371. };
  11372. Camera.prototype.serialize = function () {
  11373. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11374. // Type
  11375. serializationObject.type = this.getTypeName();
  11376. // Parent
  11377. if (this.parent) {
  11378. serializationObject.parentId = this.parent.id;
  11379. }
  11380. if (this.inputs) {
  11381. this.inputs.serialize(serializationObject);
  11382. }
  11383. // Animations
  11384. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11385. serializationObject.ranges = this.serializeAnimationRanges();
  11386. return serializationObject;
  11387. };
  11388. Camera.prototype.getTypeName = function () {
  11389. return "Camera";
  11390. };
  11391. Camera.prototype.clone = function (name) {
  11392. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11393. };
  11394. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11395. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11396. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11397. switch (type) {
  11398. case "ArcRotateCamera":
  11399. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11400. case "DeviceOrientationCamera":
  11401. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11402. case "FollowCamera":
  11403. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11404. case "ArcFollowCamera":
  11405. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11406. case "GamepadCamera":
  11407. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11408. case "TouchCamera":
  11409. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11410. case "VirtualJoysticksCamera":
  11411. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11412. case "WebVRFreeCamera":
  11413. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11414. case "VRDeviceOrientationFreeCamera":
  11415. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11416. case "AnaglyphArcRotateCamera":
  11417. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11418. case "AnaglyphFreeCamera":
  11419. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11420. case "AnaglyphGamepadCamera":
  11421. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11422. case "AnaglyphUniversalCamera":
  11423. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11424. case "StereoscopicArcRotateCamera":
  11425. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11426. case "StereoscopicFreeCamera":
  11427. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11428. case "StereoscopicGamepadCamera":
  11429. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11430. case "StereoscopicUniversalCamera":
  11431. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11432. case "FreeCamera":
  11433. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11434. default:
  11435. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11436. }
  11437. };
  11438. Camera.Parse = function (parsedCamera, scene) {
  11439. var type = parsedCamera.type;
  11440. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11441. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11442. // Parent
  11443. if (parsedCamera.parentId) {
  11444. camera._waitingParentId = parsedCamera.parentId;
  11445. }
  11446. //If camera has an input manager, let it parse inputs settings
  11447. if (camera.inputs) {
  11448. camera.inputs.parse(parsedCamera);
  11449. camera._setupInputs();
  11450. }
  11451. // Target
  11452. if (parsedCamera.target) {
  11453. if (camera.setTarget) {
  11454. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11455. }
  11456. }
  11457. // Apply 3d rig, when found
  11458. if (parsedCamera.cameraRigMode) {
  11459. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11460. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11461. }
  11462. // Animations
  11463. if (parsedCamera.animations) {
  11464. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11465. var parsedAnimation = parsedCamera.animations[animationIndex];
  11466. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11467. }
  11468. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11469. }
  11470. if (parsedCamera.autoAnimate) {
  11471. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11472. }
  11473. return camera;
  11474. };
  11475. // Statics
  11476. Camera._PERSPECTIVE_CAMERA = 0;
  11477. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11478. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11479. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11480. Camera._RIG_MODE_NONE = 0;
  11481. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11482. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11483. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11484. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11485. Camera._RIG_MODE_VR = 20;
  11486. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11487. __decorate([
  11488. BABYLON.serializeAsVector3()
  11489. ], Camera.prototype, "position", void 0);
  11490. __decorate([
  11491. BABYLON.serializeAsVector3()
  11492. ], Camera.prototype, "upVector", void 0);
  11493. __decorate([
  11494. BABYLON.serialize()
  11495. ], Camera.prototype, "orthoLeft", void 0);
  11496. __decorate([
  11497. BABYLON.serialize()
  11498. ], Camera.prototype, "orthoRight", void 0);
  11499. __decorate([
  11500. BABYLON.serialize()
  11501. ], Camera.prototype, "orthoBottom", void 0);
  11502. __decorate([
  11503. BABYLON.serialize()
  11504. ], Camera.prototype, "orthoTop", void 0);
  11505. __decorate([
  11506. BABYLON.serialize()
  11507. ], Camera.prototype, "fov", void 0);
  11508. __decorate([
  11509. BABYLON.serialize()
  11510. ], Camera.prototype, "minZ", void 0);
  11511. __decorate([
  11512. BABYLON.serialize()
  11513. ], Camera.prototype, "maxZ", void 0);
  11514. __decorate([
  11515. BABYLON.serialize()
  11516. ], Camera.prototype, "inertia", void 0);
  11517. __decorate([
  11518. BABYLON.serialize()
  11519. ], Camera.prototype, "mode", void 0);
  11520. __decorate([
  11521. BABYLON.serialize()
  11522. ], Camera.prototype, "layerMask", void 0);
  11523. __decorate([
  11524. BABYLON.serialize()
  11525. ], Camera.prototype, "fovMode", void 0);
  11526. __decorate([
  11527. BABYLON.serialize()
  11528. ], Camera.prototype, "cameraRigMode", void 0);
  11529. __decorate([
  11530. BABYLON.serialize()
  11531. ], Camera.prototype, "interaxialDistance", void 0);
  11532. __decorate([
  11533. BABYLON.serialize()
  11534. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11535. return Camera;
  11536. })(BABYLON.Node);
  11537. BABYLON.Camera = Camera;
  11538. })(BABYLON || (BABYLON = {}));
  11539. var BABYLON;
  11540. (function (BABYLON) {
  11541. BABYLON.CameraInputTypes = {};
  11542. var CameraInputsManager = (function () {
  11543. function CameraInputsManager(camera) {
  11544. this.attached = {};
  11545. this.camera = camera;
  11546. this.checkInputs = function () { };
  11547. }
  11548. CameraInputsManager.prototype.add = function (input) {
  11549. var type = input.getSimpleName();
  11550. if (this.attached[type]) {
  11551. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11552. return;
  11553. }
  11554. this.attached[type] = input;
  11555. input.camera = this.camera;
  11556. //for checkInputs, we are dynamically creating a function
  11557. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11558. if (input.checkInputs) {
  11559. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11560. }
  11561. if (this.attachedElement) {
  11562. input.attachControl(this.attachedElement);
  11563. }
  11564. };
  11565. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11566. for (var cam in this.attached) {
  11567. var input = this.attached[cam];
  11568. if (input === inputToRemove) {
  11569. input.detachControl(this.attachedElement);
  11570. delete this.attached[cam];
  11571. this.rebuildInputCheck();
  11572. }
  11573. }
  11574. };
  11575. CameraInputsManager.prototype.removeByType = function (inputType) {
  11576. for (var cam in this.attached) {
  11577. var input = this.attached[cam];
  11578. if (input.getTypeName() === inputType) {
  11579. input.detachControl(this.attachedElement);
  11580. delete this.attached[cam];
  11581. this.rebuildInputCheck();
  11582. }
  11583. }
  11584. };
  11585. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11586. var current = this.checkInputs;
  11587. return function () {
  11588. current();
  11589. fn();
  11590. };
  11591. };
  11592. CameraInputsManager.prototype.attachInput = function (input) {
  11593. input.attachControl(this.attachedElement, this.noPreventDefault);
  11594. };
  11595. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11596. if (this.attachedElement) {
  11597. return;
  11598. }
  11599. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11600. this.attachedElement = element;
  11601. this.noPreventDefault = noPreventDefault;
  11602. for (var cam in this.attached) {
  11603. var input = this.attached[cam];
  11604. this.attached[cam].attachControl(element, noPreventDefault);
  11605. }
  11606. };
  11607. CameraInputsManager.prototype.detachElement = function (element) {
  11608. if (this.attachedElement !== element) {
  11609. return;
  11610. }
  11611. for (var cam in this.attached) {
  11612. var input = this.attached[cam];
  11613. this.attached[cam].detachControl(element);
  11614. }
  11615. this.attachedElement = null;
  11616. };
  11617. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11618. this.checkInputs = function () { };
  11619. for (var cam in this.attached) {
  11620. var input = this.attached[cam];
  11621. if (input.checkInputs) {
  11622. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11623. }
  11624. }
  11625. };
  11626. CameraInputsManager.prototype.clear = function () {
  11627. if (this.attachedElement) {
  11628. this.detachElement(this.attachedElement);
  11629. }
  11630. this.attached = {};
  11631. this.attachedElement = null;
  11632. this.checkInputs = function () { };
  11633. };
  11634. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11635. var inputs = {};
  11636. for (var cam in this.attached) {
  11637. var input = this.attached[cam];
  11638. var res = BABYLON.SerializationHelper.Serialize(input);
  11639. inputs[input.getTypeName()] = res;
  11640. }
  11641. serializedCamera.inputsmgr = inputs;
  11642. };
  11643. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11644. var parsedInputs = parsedCamera.inputsmgr;
  11645. if (parsedInputs) {
  11646. this.clear();
  11647. for (var n in parsedInputs) {
  11648. var construct = BABYLON.CameraInputTypes[n];
  11649. if (construct) {
  11650. var parsedinput = parsedInputs[n];
  11651. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11652. this.add(input);
  11653. }
  11654. }
  11655. }
  11656. else {
  11657. //2016-03-08 this part is for managing backward compatibility
  11658. for (var n in this.attached) {
  11659. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11660. if (construct) {
  11661. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11662. this.remove(this.attached[n]);
  11663. this.add(input);
  11664. }
  11665. }
  11666. }
  11667. };
  11668. return CameraInputsManager;
  11669. })();
  11670. BABYLON.CameraInputsManager = CameraInputsManager;
  11671. })(BABYLON || (BABYLON = {}));
  11672. var BABYLON;
  11673. (function (BABYLON) {
  11674. var FreeCameraMouseInput = (function () {
  11675. function FreeCameraMouseInput(touchEnabled) {
  11676. if (touchEnabled === void 0) { touchEnabled = true; }
  11677. this.touchEnabled = touchEnabled;
  11678. this.angularSensibility = 2000.0;
  11679. }
  11680. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11681. var _this = this;
  11682. if (!this._pointerInput) {
  11683. var camera = this.camera;
  11684. var engine = this.camera.getEngine();
  11685. this._pointerInput = function (p, s) {
  11686. var evt = p.event;
  11687. if (!_this.touchEnabled && evt.pointerType === "touch") {
  11688. return;
  11689. }
  11690. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11691. try {
  11692. evt.srcElement.setPointerCapture(evt.pointerId);
  11693. }
  11694. catch (e) {
  11695. }
  11696. _this.previousPosition = {
  11697. x: evt.clientX,
  11698. y: evt.clientY
  11699. };
  11700. if (!noPreventDefault) {
  11701. evt.preventDefault();
  11702. }
  11703. }
  11704. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11705. try {
  11706. evt.srcElement.releasePointerCapture(evt.pointerId);
  11707. }
  11708. catch (e) {
  11709. }
  11710. _this.previousPosition = null;
  11711. if (!noPreventDefault) {
  11712. evt.preventDefault();
  11713. }
  11714. }
  11715. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11716. if (!_this.previousPosition && !engine.isPointerLock) {
  11717. return;
  11718. }
  11719. var offsetX;
  11720. var offsetY;
  11721. if (!engine.isPointerLock) {
  11722. offsetX = evt.clientX - _this.previousPosition.x;
  11723. offsetY = evt.clientY - _this.previousPosition.y;
  11724. }
  11725. else {
  11726. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11727. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11728. }
  11729. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11730. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11731. _this.previousPosition = {
  11732. x: evt.clientX,
  11733. y: evt.clientY
  11734. };
  11735. if (!noPreventDefault) {
  11736. evt.preventDefault();
  11737. }
  11738. }
  11739. };
  11740. }
  11741. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11742. };
  11743. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11744. if (this._observer && element) {
  11745. this.camera.getScene().onPointerObservable.remove(this._observer);
  11746. this._observer = null;
  11747. this.previousPosition = null;
  11748. }
  11749. };
  11750. FreeCameraMouseInput.prototype.getTypeName = function () {
  11751. return "FreeCameraMouseInput";
  11752. };
  11753. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11754. return "mouse";
  11755. };
  11756. __decorate([
  11757. BABYLON.serialize()
  11758. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11759. return FreeCameraMouseInput;
  11760. })();
  11761. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11762. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11763. })(BABYLON || (BABYLON = {}));
  11764. var BABYLON;
  11765. (function (BABYLON) {
  11766. var FreeCameraKeyboardMoveInput = (function () {
  11767. function FreeCameraKeyboardMoveInput() {
  11768. this._keys = [];
  11769. this.keysUp = [38];
  11770. this.keysDown = [40];
  11771. this.keysLeft = [37];
  11772. this.keysRight = [39];
  11773. }
  11774. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11775. var _this = this;
  11776. if (!this._onKeyDown) {
  11777. this._onKeyDown = function (evt) {
  11778. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11779. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11780. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11781. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11782. var index = _this._keys.indexOf(evt.keyCode);
  11783. if (index === -1) {
  11784. _this._keys.push(evt.keyCode);
  11785. }
  11786. if (!noPreventDefault) {
  11787. evt.preventDefault();
  11788. }
  11789. }
  11790. };
  11791. this._onKeyUp = function (evt) {
  11792. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11793. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11794. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11795. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11796. var index = _this._keys.indexOf(evt.keyCode);
  11797. if (index >= 0) {
  11798. _this._keys.splice(index, 1);
  11799. }
  11800. if (!noPreventDefault) {
  11801. evt.preventDefault();
  11802. }
  11803. }
  11804. };
  11805. BABYLON.Tools.RegisterTopRootEvents([
  11806. { name: "keydown", handler: this._onKeyDown },
  11807. { name: "keyup", handler: this._onKeyUp },
  11808. { name: "blur", handler: this._onLostFocus }
  11809. ]);
  11810. }
  11811. };
  11812. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11813. if (this._onKeyDown) {
  11814. BABYLON.Tools.UnregisterTopRootEvents([
  11815. { name: "keydown", handler: this._onKeyDown },
  11816. { name: "keyup", handler: this._onKeyUp },
  11817. { name: "blur", handler: this._onLostFocus }
  11818. ]);
  11819. this._keys = [];
  11820. this._onKeyDown = null;
  11821. this._onKeyUp = null;
  11822. }
  11823. };
  11824. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11825. if (this._onKeyDown) {
  11826. var camera = this.camera;
  11827. // Keyboard
  11828. for (var index = 0; index < this._keys.length; index++) {
  11829. var keyCode = this._keys[index];
  11830. var speed = camera._computeLocalCameraSpeed();
  11831. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11832. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11833. }
  11834. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11835. camera._localDirection.copyFromFloats(0, 0, speed);
  11836. }
  11837. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11838. camera._localDirection.copyFromFloats(speed, 0, 0);
  11839. }
  11840. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11841. camera._localDirection.copyFromFloats(0, 0, -speed);
  11842. }
  11843. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11844. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11845. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11846. }
  11847. }
  11848. };
  11849. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11850. return "FreeCameraKeyboardMoveInput";
  11851. };
  11852. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11853. this._keys = [];
  11854. };
  11855. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11856. return "keyboard";
  11857. };
  11858. __decorate([
  11859. BABYLON.serialize()
  11860. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11861. __decorate([
  11862. BABYLON.serialize()
  11863. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11864. __decorate([
  11865. BABYLON.serialize()
  11866. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11867. __decorate([
  11868. BABYLON.serialize()
  11869. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11870. return FreeCameraKeyboardMoveInput;
  11871. })();
  11872. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11873. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11874. })(BABYLON || (BABYLON = {}));
  11875. var BABYLON;
  11876. (function (BABYLON) {
  11877. var FreeCameraTouchInput = (function () {
  11878. function FreeCameraTouchInput() {
  11879. this._offsetX = null;
  11880. this._offsetY = null;
  11881. this._pointerCount = 0;
  11882. this._pointerPressed = [];
  11883. this.touchAngularSensibility = 200000.0;
  11884. this.touchMoveSensibility = 250.0;
  11885. }
  11886. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11887. var _this = this;
  11888. var previousPosition;
  11889. if (this._pointerInput === undefined) {
  11890. this._onLostFocus = function (evt) {
  11891. _this._offsetX = null;
  11892. _this._offsetY = null;
  11893. };
  11894. this._pointerInput = function (p, s) {
  11895. var evt = p.event;
  11896. if (evt.pointerType === "mouse") {
  11897. return;
  11898. }
  11899. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11900. if (!noPreventDefault) {
  11901. evt.preventDefault();
  11902. }
  11903. _this._pointerPressed.push(evt.pointerId);
  11904. if (_this._pointerPressed.length !== 1) {
  11905. return;
  11906. }
  11907. previousPosition = {
  11908. x: evt.clientX,
  11909. y: evt.clientY
  11910. };
  11911. }
  11912. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11913. if (!noPreventDefault) {
  11914. evt.preventDefault();
  11915. }
  11916. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11917. if (index === -1) {
  11918. return;
  11919. }
  11920. _this._pointerPressed.splice(index, 1);
  11921. if (index != 0) {
  11922. return;
  11923. }
  11924. previousPosition = null;
  11925. _this._offsetX = null;
  11926. _this._offsetY = null;
  11927. }
  11928. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11929. if (!noPreventDefault) {
  11930. evt.preventDefault();
  11931. }
  11932. if (!previousPosition) {
  11933. return;
  11934. }
  11935. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11936. if (index != 0) {
  11937. return;
  11938. }
  11939. _this._offsetX = evt.clientX - previousPosition.x;
  11940. _this._offsetY = -(evt.clientY - previousPosition.y);
  11941. }
  11942. };
  11943. }
  11944. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11945. element.addEventListener("blur", this._onLostFocus);
  11946. };
  11947. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11948. if (this._pointerInput && element) {
  11949. this.camera.getScene().onPointerObservable.remove(this._observer);
  11950. this._observer = null;
  11951. element.removeEventListener("blur", this._onLostFocus);
  11952. this._onLostFocus = null;
  11953. this._pointerPressed = [];
  11954. this._offsetX = null;
  11955. this._offsetY = null;
  11956. this._pointerCount = 0;
  11957. }
  11958. };
  11959. FreeCameraTouchInput.prototype.checkInputs = function () {
  11960. if (this._offsetX) {
  11961. var camera = this.camera;
  11962. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11963. if (this._pointerPressed.length > 1) {
  11964. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11965. }
  11966. else {
  11967. var speed = camera._computeLocalCameraSpeed();
  11968. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11969. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11970. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11971. }
  11972. }
  11973. };
  11974. FreeCameraTouchInput.prototype.getTypeName = function () {
  11975. return "FreeCameraTouchInput";
  11976. };
  11977. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11978. return "touch";
  11979. };
  11980. __decorate([
  11981. BABYLON.serialize()
  11982. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11983. __decorate([
  11984. BABYLON.serialize()
  11985. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11986. return FreeCameraTouchInput;
  11987. })();
  11988. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11989. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11990. })(BABYLON || (BABYLON = {}));
  11991. var BABYLON;
  11992. (function (BABYLON) {
  11993. var FreeCameraDeviceOrientationInput = (function () {
  11994. function FreeCameraDeviceOrientationInput() {
  11995. this._offsetX = null;
  11996. this._offsetY = null;
  11997. this._orientationGamma = 0;
  11998. this._orientationBeta = 0;
  11999. this._initialOrientationGamma = 0;
  12000. this._initialOrientationBeta = 0;
  12001. this.angularSensibility = 10000.0;
  12002. this.moveSensibility = 50.0;
  12003. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  12004. this._orientationChanged = this.orientationChanged.bind(this);
  12005. }
  12006. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12007. window.addEventListener("resize", this._resetOrientationGamma, false);
  12008. window.addEventListener("deviceorientation", this._orientationChanged);
  12009. };
  12010. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  12011. this._initialOrientationGamma = null;
  12012. };
  12013. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  12014. if (!this._initialOrientationGamma) {
  12015. this._initialOrientationGamma = evt.gamma;
  12016. this._initialOrientationBeta = evt.beta;
  12017. }
  12018. this._orientationGamma = evt.gamma;
  12019. this._orientationBeta = evt.beta;
  12020. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  12021. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  12022. };
  12023. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  12024. window.removeEventListener("resize", this._resetOrientationGamma);
  12025. window.removeEventListener("deviceorientation", this._orientationChanged);
  12026. this._orientationGamma = 0;
  12027. this._orientationBeta = 0;
  12028. this._initialOrientationGamma = 0;
  12029. this._initialOrientationBeta = 0;
  12030. this._offsetX = null;
  12031. this._offsetY = null;
  12032. };
  12033. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  12034. if (!this._offsetX) {
  12035. return;
  12036. }
  12037. var camera = this.camera;
  12038. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  12039. var speed = camera._computeLocalCameraSpeed();
  12040. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  12041. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  12042. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  12043. };
  12044. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  12045. return "FreeCameraDeviceOrientationInput";
  12046. };
  12047. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  12048. return "deviceOrientation";
  12049. };
  12050. __decorate([
  12051. BABYLON.serialize()
  12052. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  12053. __decorate([
  12054. BABYLON.serialize()
  12055. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  12056. return FreeCameraDeviceOrientationInput;
  12057. })();
  12058. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  12059. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  12060. })(BABYLON || (BABYLON = {}));
  12061. var BABYLON;
  12062. (function (BABYLON) {
  12063. var FreeCameraVRDeviceOrientationInput = (function () {
  12064. function FreeCameraVRDeviceOrientationInput() {
  12065. this.alphaCorrection = 1;
  12066. this.betaCorrection = 1;
  12067. this.gammaCorrection = 1;
  12068. this._alpha = 0;
  12069. this._beta = 0;
  12070. this._gamma = 0;
  12071. this._dirty = false;
  12072. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12073. }
  12074. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12075. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12076. };
  12077. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12078. var camera = this.camera;
  12079. this._alpha = +evt.alpha | 0;
  12080. this._beta = +evt.beta | 0;
  12081. this._gamma = +evt.gamma | 0;
  12082. this._dirty = true;
  12083. };
  12084. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12085. if (this._dirty) {
  12086. this._dirty = false;
  12087. var rotationX = this._gamma;
  12088. if (rotationX < 0) {
  12089. rotationX = 90 + rotationX;
  12090. }
  12091. else {
  12092. // Incline it in the correct angle.
  12093. rotationX = 270 - rotationX;
  12094. }
  12095. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12096. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12097. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12098. }
  12099. };
  12100. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12101. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12102. };
  12103. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12104. return "FreeCameraVRDeviceOrientationInput";
  12105. };
  12106. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12107. return "VRDeviceOrientation";
  12108. };
  12109. return FreeCameraVRDeviceOrientationInput;
  12110. })();
  12111. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12112. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12113. })(BABYLON || (BABYLON = {}));
  12114. var BABYLON;
  12115. (function (BABYLON) {
  12116. var FreeCameraGamepadInput = (function () {
  12117. function FreeCameraGamepadInput() {
  12118. this.gamepadAngularSensibility = 200;
  12119. this.gamepadMoveSensibility = 40;
  12120. }
  12121. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12122. var _this = this;
  12123. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12124. };
  12125. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12126. if (this._gamepads) {
  12127. this._gamepads.dispose();
  12128. }
  12129. this.gamepad = null;
  12130. };
  12131. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12132. if (this.gamepad) {
  12133. var camera = this.camera;
  12134. var LSValues = this.gamepad.leftStick;
  12135. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12136. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12137. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12138. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12139. var RSValues = this.gamepad.rightStick;
  12140. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12141. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12142. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12143. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12144. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12145. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12146. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12147. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12148. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12149. }
  12150. };
  12151. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12152. // Only the first gamepad can control the camera
  12153. if (gamepad.index === 0) {
  12154. this.gamepad = gamepad;
  12155. }
  12156. };
  12157. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12158. return "FreeCameraGamepadInput";
  12159. };
  12160. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12161. return "gamepad";
  12162. };
  12163. __decorate([
  12164. BABYLON.serialize()
  12165. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12166. __decorate([
  12167. BABYLON.serialize()
  12168. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12169. return FreeCameraGamepadInput;
  12170. })();
  12171. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12172. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12173. })(BABYLON || (BABYLON = {}));
  12174. var BABYLON;
  12175. (function (BABYLON) {
  12176. var FreeCameraVirtualJoystickInput = (function () {
  12177. function FreeCameraVirtualJoystickInput() {
  12178. }
  12179. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12180. return this._leftjoystick;
  12181. };
  12182. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12183. return this._rightjoystick;
  12184. };
  12185. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12186. if (this._leftjoystick) {
  12187. var camera = this.camera;
  12188. var speed = camera._computeLocalCameraSpeed() * 50;
  12189. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12190. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12191. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12192. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12193. if (!this._leftjoystick.pressed) {
  12194. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12195. }
  12196. if (!this._rightjoystick.pressed) {
  12197. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12198. }
  12199. }
  12200. };
  12201. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12202. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12203. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12204. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12205. this._leftjoystick.setJoystickSensibility(0.15);
  12206. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12207. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12208. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12209. this._rightjoystick.reverseUpDown = true;
  12210. this._rightjoystick.setJoystickSensibility(0.05);
  12211. this._rightjoystick.setJoystickColor("yellow");
  12212. };
  12213. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12214. this._leftjoystick.releaseCanvas();
  12215. this._rightjoystick.releaseCanvas();
  12216. };
  12217. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12218. return "FreeCameraVirtualJoystickInput";
  12219. };
  12220. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12221. return "virtualJoystick";
  12222. };
  12223. return FreeCameraVirtualJoystickInput;
  12224. })();
  12225. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12226. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12227. })(BABYLON || (BABYLON = {}));
  12228. var BABYLON;
  12229. (function (BABYLON) {
  12230. var ArcRotateCameraKeyboardMoveInput = (function () {
  12231. function ArcRotateCameraKeyboardMoveInput() {
  12232. this._keys = [];
  12233. this.keysUp = [38];
  12234. this.keysDown = [40];
  12235. this.keysLeft = [37];
  12236. this.keysRight = [39];
  12237. }
  12238. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12239. var _this = this;
  12240. this._onKeyDown = function (evt) {
  12241. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12242. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12243. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12244. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12245. var index = _this._keys.indexOf(evt.keyCode);
  12246. if (index === -1) {
  12247. _this._keys.push(evt.keyCode);
  12248. }
  12249. if (evt.preventDefault) {
  12250. if (!noPreventDefault) {
  12251. evt.preventDefault();
  12252. }
  12253. }
  12254. }
  12255. };
  12256. this._onKeyUp = function (evt) {
  12257. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12258. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12259. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12260. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12261. var index = _this._keys.indexOf(evt.keyCode);
  12262. if (index >= 0) {
  12263. _this._keys.splice(index, 1);
  12264. }
  12265. if (evt.preventDefault) {
  12266. if (!noPreventDefault) {
  12267. evt.preventDefault();
  12268. }
  12269. }
  12270. }
  12271. };
  12272. this._onLostFocus = function () {
  12273. _this._keys = [];
  12274. };
  12275. BABYLON.Tools.RegisterTopRootEvents([
  12276. { name: "keydown", handler: this._onKeyDown },
  12277. { name: "keyup", handler: this._onKeyUp },
  12278. { name: "blur", handler: this._onLostFocus }
  12279. ]);
  12280. };
  12281. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12282. BABYLON.Tools.UnregisterTopRootEvents([
  12283. { name: "keydown", handler: this._onKeyDown },
  12284. { name: "keyup", handler: this._onKeyUp },
  12285. { name: "blur", handler: this._onLostFocus }
  12286. ]);
  12287. this._keys = [];
  12288. this._onKeyDown = null;
  12289. this._onKeyUp = null;
  12290. this._onLostFocus = null;
  12291. };
  12292. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12293. if (this._onKeyDown) {
  12294. var camera = this.camera;
  12295. for (var index = 0; index < this._keys.length; index++) {
  12296. var keyCode = this._keys[index];
  12297. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12298. camera.inertialAlphaOffset -= 0.01;
  12299. }
  12300. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12301. camera.inertialBetaOffset -= 0.01;
  12302. }
  12303. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12304. camera.inertialAlphaOffset += 0.01;
  12305. }
  12306. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12307. camera.inertialBetaOffset += 0.01;
  12308. }
  12309. }
  12310. }
  12311. };
  12312. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12313. return "ArcRotateCameraKeyboardMoveInput";
  12314. };
  12315. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12316. return "keyboard";
  12317. };
  12318. __decorate([
  12319. BABYLON.serialize()
  12320. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12321. __decorate([
  12322. BABYLON.serialize()
  12323. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12324. __decorate([
  12325. BABYLON.serialize()
  12326. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12327. __decorate([
  12328. BABYLON.serialize()
  12329. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12330. return ArcRotateCameraKeyboardMoveInput;
  12331. })();
  12332. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12333. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12334. })(BABYLON || (BABYLON = {}));
  12335. var BABYLON;
  12336. (function (BABYLON) {
  12337. var ArcRotateCameraMouseWheelInput = (function () {
  12338. function ArcRotateCameraMouseWheelInput() {
  12339. this.wheelPrecision = 3.0;
  12340. }
  12341. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12342. var _this = this;
  12343. this._wheel = function (p, s) {
  12344. //sanity check - this should be a PointerWheel event.
  12345. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12346. return;
  12347. var event = p.event;
  12348. var delta = 0;
  12349. if (event.wheelDelta) {
  12350. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12351. }
  12352. else if (event.detail) {
  12353. delta = -event.detail / _this.wheelPrecision;
  12354. }
  12355. if (delta)
  12356. _this.camera.inertialRadiusOffset += delta;
  12357. if (event.preventDefault) {
  12358. if (!noPreventDefault) {
  12359. event.preventDefault();
  12360. }
  12361. }
  12362. };
  12363. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12364. };
  12365. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12366. if (this._observer && element) {
  12367. this.camera.getScene().onPointerObservable.remove(this._observer);
  12368. this._observer = null;
  12369. this._wheel = null;
  12370. }
  12371. };
  12372. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12373. return "ArcRotateCameraMouseWheelInput";
  12374. };
  12375. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12376. return "mousewheel";
  12377. };
  12378. __decorate([
  12379. BABYLON.serialize()
  12380. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12381. return ArcRotateCameraMouseWheelInput;
  12382. })();
  12383. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12384. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12385. })(BABYLON || (BABYLON = {}));
  12386. var BABYLON;
  12387. (function (BABYLON) {
  12388. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12389. var ArcRotateCameraPointersInput = (function () {
  12390. function ArcRotateCameraPointersInput() {
  12391. this.angularSensibilityX = 1000.0;
  12392. this.angularSensibilityY = 1000.0;
  12393. this.pinchPrecision = 6.0;
  12394. this.panningSensibility = 50.0;
  12395. this._isRightClick = false;
  12396. this._isCtrlPushed = false;
  12397. this.pinchInwards = true;
  12398. }
  12399. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12400. var _this = this;
  12401. var engine = this.camera.getEngine();
  12402. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12403. var pointA, pointB;
  12404. var previousPinchDistance = 0;
  12405. this._pointerInput = function (p, s) {
  12406. var evt = p.event;
  12407. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12408. try {
  12409. evt.srcElement.setPointerCapture(evt.pointerId);
  12410. }
  12411. catch (e) {
  12412. }
  12413. // Manage panning with right click
  12414. _this._isRightClick = evt.button === 2;
  12415. // manage pointers
  12416. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  12417. if (pointA === undefined) {
  12418. pointA = cacheSoloPointer;
  12419. }
  12420. else if (pointB === undefined) {
  12421. pointB = cacheSoloPointer;
  12422. }
  12423. if (!noPreventDefault) {
  12424. evt.preventDefault();
  12425. }
  12426. }
  12427. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12428. try {
  12429. evt.srcElement.releasePointerCapture(evt.pointerId);
  12430. }
  12431. catch (e) {
  12432. }
  12433. cacheSoloPointer = null;
  12434. previousPinchDistance = 0;
  12435. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12436. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12437. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12438. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12439. pointA = pointB = undefined;
  12440. if (!noPreventDefault) {
  12441. evt.preventDefault();
  12442. }
  12443. }
  12444. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12445. if (!noPreventDefault) {
  12446. evt.preventDefault();
  12447. }
  12448. // One button down
  12449. if (pointA && pointB === undefined) {
  12450. if (_this.panningSensibility !== 0 &&
  12451. ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) ||
  12452. (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12453. _this.camera
  12454. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12455. _this.camera
  12456. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12457. }
  12458. else {
  12459. var offsetX = evt.clientX - cacheSoloPointer.x;
  12460. var offsetY = evt.clientY - cacheSoloPointer.y;
  12461. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12462. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12463. }
  12464. cacheSoloPointer.x = evt.clientX;
  12465. cacheSoloPointer.y = evt.clientY;
  12466. }
  12467. else if (pointA && pointB) {
  12468. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12469. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  12470. ed.x = evt.clientX;
  12471. ed.y = evt.clientY;
  12472. var direction = _this.pinchInwards ? 1 : -1;
  12473. var distX = pointA.x - pointB.x;
  12474. var distY = pointA.y - pointB.y;
  12475. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12476. if (previousPinchDistance === 0) {
  12477. previousPinchDistance = pinchSquaredDistance;
  12478. return;
  12479. }
  12480. if (pinchSquaredDistance !== previousPinchDistance) {
  12481. _this.camera
  12482. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  12483. (_this.pinchPrecision *
  12484. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  12485. direction);
  12486. previousPinchDistance = pinchSquaredDistance;
  12487. }
  12488. }
  12489. }
  12490. };
  12491. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12492. this._onContextMenu = function (evt) {
  12493. evt.preventDefault();
  12494. };
  12495. if (!this.camera._useCtrlForPanning) {
  12496. element.addEventListener("contextmenu", this._onContextMenu, false);
  12497. }
  12498. this._onLostFocus = function () {
  12499. //this._keys = [];
  12500. pointA = pointB = undefined;
  12501. previousPinchDistance = 0;
  12502. cacheSoloPointer = null;
  12503. };
  12504. this._onKeyDown = function (evt) {
  12505. _this._isCtrlPushed = evt.ctrlKey;
  12506. };
  12507. this._onKeyUp = function (evt) {
  12508. _this._isCtrlPushed = evt.ctrlKey;
  12509. };
  12510. this._onMouseMove = function (evt) {
  12511. if (!engine.isPointerLock) {
  12512. return;
  12513. }
  12514. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12515. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12516. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12517. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12518. if (!noPreventDefault) {
  12519. evt.preventDefault();
  12520. }
  12521. };
  12522. this._onGestureStart = function (e) {
  12523. if (window.MSGesture === undefined) {
  12524. return;
  12525. }
  12526. if (!_this._MSGestureHandler) {
  12527. _this._MSGestureHandler = new MSGesture();
  12528. _this._MSGestureHandler.target = element;
  12529. }
  12530. _this._MSGestureHandler.addPointer(e.pointerId);
  12531. };
  12532. this._onGesture = function (e) {
  12533. _this.camera.radius *= e.scale;
  12534. if (e.preventDefault) {
  12535. if (!noPreventDefault) {
  12536. e.stopPropagation();
  12537. e.preventDefault();
  12538. }
  12539. }
  12540. };
  12541. element.addEventListener("mousemove", this._onMouseMove, false);
  12542. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12543. element.addEventListener("MSGestureChange", this._onGesture, false);
  12544. BABYLON.Tools.RegisterTopRootEvents([
  12545. { name: "keydown", handler: this._onKeyDown },
  12546. { name: "keyup", handler: this._onKeyUp },
  12547. { name: "blur", handler: this._onLostFocus }
  12548. ]);
  12549. };
  12550. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12551. if (element && this._observer) {
  12552. this.camera.getScene().onPointerObservable.remove(this._observer);
  12553. this._observer = null;
  12554. element.removeEventListener("contextmenu", this._onContextMenu);
  12555. element.removeEventListener("mousemove", this._onMouseMove);
  12556. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12557. element.removeEventListener("MSGestureChange", this._onGesture);
  12558. this._isRightClick = false;
  12559. this._isCtrlPushed = false;
  12560. this.pinchInwards = true;
  12561. this._onKeyDown = null;
  12562. this._onKeyUp = null;
  12563. this._onMouseMove = null;
  12564. this._onGestureStart = null;
  12565. this._onGesture = null;
  12566. this._MSGestureHandler = null;
  12567. this._onLostFocus = null;
  12568. this._onContextMenu = null;
  12569. }
  12570. BABYLON.Tools.UnregisterTopRootEvents([
  12571. { name: "keydown", handler: this._onKeyDown },
  12572. { name: "keyup", handler: this._onKeyUp },
  12573. { name: "blur", handler: this._onLostFocus }
  12574. ]);
  12575. };
  12576. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12577. return "ArcRotateCameraPointersInput";
  12578. };
  12579. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12580. return "pointers";
  12581. };
  12582. __decorate([
  12583. BABYLON.serialize()
  12584. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12585. __decorate([
  12586. BABYLON.serialize()
  12587. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12588. __decorate([
  12589. BABYLON.serialize()
  12590. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12591. __decorate([
  12592. BABYLON.serialize()
  12593. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12594. return ArcRotateCameraPointersInput;
  12595. })();
  12596. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12597. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12598. })(BABYLON || (BABYLON = {}));
  12599. var BABYLON;
  12600. (function (BABYLON) {
  12601. var ArcRotateCameraGamepadInput = (function () {
  12602. function ArcRotateCameraGamepadInput() {
  12603. this.gamepadRotationSensibility = 80;
  12604. this.gamepadMoveSensibility = 40;
  12605. }
  12606. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12607. var _this = this;
  12608. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12609. };
  12610. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12611. if (this._gamepads) {
  12612. this._gamepads.dispose();
  12613. }
  12614. this.gamepad = null;
  12615. };
  12616. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12617. if (this.gamepad) {
  12618. var camera = this.camera;
  12619. var RSValues = this.gamepad.rightStick;
  12620. if (RSValues.x != 0) {
  12621. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12622. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12623. camera.inertialAlphaOffset += normalizedRX;
  12624. }
  12625. }
  12626. if (RSValues.y != 0) {
  12627. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12628. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12629. camera.inertialBetaOffset += normalizedRY;
  12630. }
  12631. }
  12632. var LSValues = this.gamepad.leftStick;
  12633. if (LSValues.y != 0) {
  12634. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12635. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12636. this.camera.inertialRadiusOffset -= normalizedLY;
  12637. }
  12638. }
  12639. }
  12640. };
  12641. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12642. // Only the first gamepad can control the camera
  12643. if (gamepad.index === 0) {
  12644. this.gamepad = gamepad;
  12645. }
  12646. };
  12647. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12648. return "ArcRotateCameraGamepadInput";
  12649. };
  12650. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12651. return "gamepad";
  12652. };
  12653. __decorate([
  12654. BABYLON.serialize()
  12655. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12656. __decorate([
  12657. BABYLON.serialize()
  12658. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12659. return ArcRotateCameraGamepadInput;
  12660. })();
  12661. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12662. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12663. })(BABYLON || (BABYLON = {}));
  12664. var BABYLON;
  12665. (function (BABYLON) {
  12666. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12667. function ArcRotateCameraVRDeviceOrientationInput() {
  12668. this.alphaCorrection = 1;
  12669. this.betaCorrection = 1;
  12670. this.gammaCorrection = 1;
  12671. this._alpha = 0;
  12672. this._beta = 0;
  12673. this._gamma = 0;
  12674. this._dirty = false;
  12675. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12676. }
  12677. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12678. this.camera.attachControl(element, noPreventDefault);
  12679. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12680. };
  12681. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12682. var camera = this.camera;
  12683. this._alpha = +evt.alpha | 0;
  12684. this._beta = +evt.beta | 0;
  12685. this._gamma = +evt.gamma | 0;
  12686. this._dirty = true;
  12687. };
  12688. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12689. if (this._dirty) {
  12690. this._dirty = false;
  12691. if (this._gamma < 0) {
  12692. this._gamma = 180 + this._gamma;
  12693. }
  12694. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12695. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12696. }
  12697. };
  12698. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12699. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12700. };
  12701. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12702. return "ArcRotateCameraVRDeviceOrientationInput";
  12703. };
  12704. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12705. return "VRDeviceOrientation";
  12706. };
  12707. return ArcRotateCameraVRDeviceOrientationInput;
  12708. })();
  12709. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12710. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12711. })(BABYLON || (BABYLON = {}));
  12712. var BABYLON;
  12713. (function (BABYLON) {
  12714. var TargetCamera = (function (_super) {
  12715. __extends(TargetCamera, _super);
  12716. function TargetCamera(name, position, scene) {
  12717. _super.call(this, name, position, scene);
  12718. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12719. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12720. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12721. this.speed = 2.0;
  12722. this.noRotationConstraint = false;
  12723. this.lockedTarget = null;
  12724. this._currentTarget = BABYLON.Vector3.Zero();
  12725. this._viewMatrix = BABYLON.Matrix.Zero();
  12726. this._camMatrix = BABYLON.Matrix.Zero();
  12727. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12728. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12729. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12730. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12731. this._lookAtTemp = BABYLON.Matrix.Zero();
  12732. this._tempMatrix = BABYLON.Matrix.Zero();
  12733. }
  12734. TargetCamera.prototype.getFrontPosition = function (distance) {
  12735. var direction = this.getTarget().subtract(this.position);
  12736. direction.normalize();
  12737. direction.scaleInPlace(distance);
  12738. return this.globalPosition.add(direction);
  12739. };
  12740. TargetCamera.prototype._getLockedTargetPosition = function () {
  12741. if (!this.lockedTarget) {
  12742. return null;
  12743. }
  12744. return this.lockedTarget.position || this.lockedTarget;
  12745. };
  12746. // Cache
  12747. TargetCamera.prototype._initCache = function () {
  12748. _super.prototype._initCache.call(this);
  12749. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12750. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12751. };
  12752. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12753. if (!ignoreParentClass) {
  12754. _super.prototype._updateCache.call(this);
  12755. }
  12756. var lockedTargetPosition = this._getLockedTargetPosition();
  12757. if (!lockedTargetPosition) {
  12758. this._cache.lockedTarget = null;
  12759. }
  12760. else {
  12761. if (!this._cache.lockedTarget) {
  12762. this._cache.lockedTarget = lockedTargetPosition.clone();
  12763. }
  12764. else {
  12765. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12766. }
  12767. }
  12768. this._cache.rotation.copyFrom(this.rotation);
  12769. };
  12770. // Synchronized
  12771. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12772. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12773. return false;
  12774. }
  12775. var lockedTargetPosition = this._getLockedTargetPosition();
  12776. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12777. && this._cache.rotation.equals(this.rotation);
  12778. };
  12779. // Methods
  12780. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12781. var engine = this.getEngine();
  12782. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12783. };
  12784. // Target
  12785. TargetCamera.prototype.setTarget = function (target) {
  12786. this.upVector.normalize();
  12787. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12788. this._camMatrix.invert();
  12789. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12790. var vDir = target.subtract(this.position);
  12791. if (vDir.x >= 0.0) {
  12792. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12793. }
  12794. else {
  12795. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12796. }
  12797. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12798. if (isNaN(this.rotation.x)) {
  12799. this.rotation.x = 0;
  12800. }
  12801. if (isNaN(this.rotation.y)) {
  12802. this.rotation.y = 0;
  12803. }
  12804. if (isNaN(this.rotation.z)) {
  12805. this.rotation.z = 0;
  12806. }
  12807. };
  12808. TargetCamera.prototype.getTarget = function () {
  12809. return this._currentTarget;
  12810. };
  12811. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12812. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12813. };
  12814. TargetCamera.prototype._updatePosition = function () {
  12815. this.position.addInPlace(this.cameraDirection);
  12816. };
  12817. TargetCamera.prototype._checkInputs = function () {
  12818. var needToMove = this._decideIfNeedsToMove();
  12819. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12820. // Move
  12821. if (needToMove) {
  12822. this._updatePosition();
  12823. }
  12824. // Rotate
  12825. if (needToRotate) {
  12826. this.rotation.x += this.cameraRotation.x;
  12827. this.rotation.y += this.cameraRotation.y;
  12828. if (!this.noRotationConstraint) {
  12829. var limit = (Math.PI / 2) * 0.95;
  12830. if (this.rotation.x > limit)
  12831. this.rotation.x = limit;
  12832. if (this.rotation.x < -limit)
  12833. this.rotation.x = -limit;
  12834. }
  12835. }
  12836. // Inertia
  12837. if (needToMove) {
  12838. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12839. this.cameraDirection.x = 0;
  12840. }
  12841. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12842. this.cameraDirection.y = 0;
  12843. }
  12844. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12845. this.cameraDirection.z = 0;
  12846. }
  12847. this.cameraDirection.scaleInPlace(this.inertia);
  12848. }
  12849. if (needToRotate) {
  12850. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12851. this.cameraRotation.x = 0;
  12852. }
  12853. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12854. this.cameraRotation.y = 0;
  12855. }
  12856. this.cameraRotation.scaleInPlace(this.inertia);
  12857. }
  12858. _super.prototype._checkInputs.call(this);
  12859. };
  12860. TargetCamera.prototype._getViewMatrix = function () {
  12861. if (!this.lockedTarget) {
  12862. // Compute
  12863. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12864. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12865. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12866. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12867. this._lookAtTemp.invert();
  12868. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12869. }
  12870. else {
  12871. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12872. }
  12873. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12874. // Computing target and final matrix
  12875. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12876. }
  12877. else {
  12878. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12879. }
  12880. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12881. return this._viewMatrix;
  12882. };
  12883. TargetCamera.prototype._getVRViewMatrix = function () {
  12884. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12885. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12886. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12887. // Computing target and final matrix
  12888. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12889. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12890. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12891. return this._viewMatrix;
  12892. };
  12893. /**
  12894. * @override
  12895. * Override Camera.createRigCamera
  12896. */
  12897. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12898. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12899. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12900. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12901. rigCamera._cameraRigParams = {};
  12902. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12903. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12904. }
  12905. return rigCamera;
  12906. }
  12907. return null;
  12908. };
  12909. /**
  12910. * @override
  12911. * Override Camera._updateRigCameras
  12912. */
  12913. TargetCamera.prototype._updateRigCameras = function () {
  12914. switch (this.cameraRigMode) {
  12915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12919. case BABYLON.Camera.RIG_MODE_VR:
  12920. var camLeft = this._rigCameras[0];
  12921. var camRight = this._rigCameras[1];
  12922. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12923. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12924. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12925. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12926. camLeft.position.copyFrom(this.position);
  12927. camRight.position.copyFrom(this.position);
  12928. }
  12929. else {
  12930. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12931. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12932. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12933. camLeft.setTarget(this.getTarget());
  12934. camRight.setTarget(this.getTarget());
  12935. }
  12936. break;
  12937. }
  12938. _super.prototype._updateRigCameras.call(this);
  12939. };
  12940. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12941. if (!this._rigCamTransformMatrix) {
  12942. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12943. }
  12944. var target = this.getTarget();
  12945. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12946. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12947. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12948. };
  12949. TargetCamera.prototype.getTypeName = function () {
  12950. return "TargetCamera";
  12951. };
  12952. __decorate([
  12953. BABYLON.serializeAsVector3()
  12954. ], TargetCamera.prototype, "rotation", void 0);
  12955. __decorate([
  12956. BABYLON.serialize()
  12957. ], TargetCamera.prototype, "speed", void 0);
  12958. __decorate([
  12959. BABYLON.serializeAsMeshReference("lockedTargetId")
  12960. ], TargetCamera.prototype, "lockedTarget", void 0);
  12961. return TargetCamera;
  12962. })(BABYLON.Camera);
  12963. BABYLON.TargetCamera = TargetCamera;
  12964. })(BABYLON || (BABYLON = {}));
  12965. var BABYLON;
  12966. (function (BABYLON) {
  12967. var FreeCamera = (function (_super) {
  12968. __extends(FreeCamera, _super);
  12969. function FreeCamera(name, position, scene) {
  12970. var _this = this;
  12971. _super.call(this, name, position, scene);
  12972. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12973. this.checkCollisions = false;
  12974. this.applyGravity = false;
  12975. this._collider = new BABYLON.Collider();
  12976. this._needMoveForGravity = false;
  12977. this._oldPosition = BABYLON.Vector3.Zero();
  12978. this._diffPosition = BABYLON.Vector3.Zero();
  12979. this._newPosition = BABYLON.Vector3.Zero();
  12980. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12981. if (collidedMesh === void 0) { collidedMesh = null; }
  12982. //TODO move this to the collision coordinator!
  12983. if (_this.getScene().workerCollisions)
  12984. newPosition.multiplyInPlace(_this._collider.radius);
  12985. var updatePosition = function (newPos) {
  12986. _this._newPosition.copyFrom(newPos);
  12987. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12988. var oldPosition = _this.position.clone();
  12989. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12990. _this.position.addInPlace(_this._diffPosition);
  12991. if (_this.onCollide && collidedMesh) {
  12992. _this.onCollide(collidedMesh);
  12993. }
  12994. }
  12995. };
  12996. updatePosition(newPosition);
  12997. };
  12998. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12999. this.inputs.addKeyboard().addMouse();
  13000. }
  13001. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  13002. //-- begin properties for backward compatibility for inputs
  13003. get: function () {
  13004. var mouse = this.inputs.attached["mouse"];
  13005. if (mouse)
  13006. return mouse.angularSensibility;
  13007. },
  13008. set: function (value) {
  13009. var mouse = this.inputs.attached["mouse"];
  13010. if (mouse)
  13011. mouse.angularSensibility = value;
  13012. },
  13013. enumerable: true,
  13014. configurable: true
  13015. });
  13016. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  13017. get: function () {
  13018. var keyboard = this.inputs.attached["keyboard"];
  13019. if (keyboard)
  13020. return keyboard.keysUp;
  13021. },
  13022. set: function (value) {
  13023. var keyboard = this.inputs.attached["keyboard"];
  13024. if (keyboard)
  13025. keyboard.keysUp = value;
  13026. },
  13027. enumerable: true,
  13028. configurable: true
  13029. });
  13030. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  13031. get: function () {
  13032. var keyboard = this.inputs.attached["keyboard"];
  13033. if (keyboard)
  13034. return keyboard.keysDown;
  13035. },
  13036. set: function (value) {
  13037. var keyboard = this.inputs.attached["keyboard"];
  13038. if (keyboard)
  13039. keyboard.keysDown = value;
  13040. },
  13041. enumerable: true,
  13042. configurable: true
  13043. });
  13044. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  13045. get: function () {
  13046. var keyboard = this.inputs.attached["keyboard"];
  13047. if (keyboard)
  13048. return keyboard.keysLeft;
  13049. },
  13050. set: function (value) {
  13051. var keyboard = this.inputs.attached["keyboard"];
  13052. if (keyboard)
  13053. keyboard.keysLeft = value;
  13054. },
  13055. enumerable: true,
  13056. configurable: true
  13057. });
  13058. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  13059. get: function () {
  13060. var keyboard = this.inputs.attached["keyboard"];
  13061. if (keyboard)
  13062. return keyboard.keysRight;
  13063. },
  13064. set: function (value) {
  13065. var keyboard = this.inputs.attached["keyboard"];
  13066. if (keyboard)
  13067. keyboard.keysRight = value;
  13068. },
  13069. enumerable: true,
  13070. configurable: true
  13071. });
  13072. // Controls
  13073. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  13074. this.inputs.attachElement(element, noPreventDefault);
  13075. };
  13076. FreeCamera.prototype.detachControl = function (element) {
  13077. this.inputs.detachElement(element);
  13078. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13079. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13080. };
  13081. FreeCamera.prototype._collideWithWorld = function (velocity) {
  13082. var globalPosition;
  13083. if (this.parent) {
  13084. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  13085. }
  13086. else {
  13087. globalPosition = this.position;
  13088. }
  13089. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13090. this._collider.radius = this.ellipsoid;
  13091. //no need for clone, as long as gravity is not on.
  13092. var actualVelocity = velocity;
  13093. //add gravity to the velocity to prevent the dual-collision checking
  13094. if (this.applyGravity) {
  13095. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13096. actualVelocity = velocity.add(this.getScene().gravity);
  13097. }
  13098. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13099. };
  13100. FreeCamera.prototype._checkInputs = function () {
  13101. if (!this._localDirection) {
  13102. this._localDirection = BABYLON.Vector3.Zero();
  13103. this._transformedDirection = BABYLON.Vector3.Zero();
  13104. }
  13105. this.inputs.checkInputs();
  13106. _super.prototype._checkInputs.call(this);
  13107. };
  13108. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13109. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13110. };
  13111. FreeCamera.prototype._updatePosition = function () {
  13112. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13113. this._collideWithWorld(this.cameraDirection);
  13114. }
  13115. else {
  13116. this.position.addInPlace(this.cameraDirection);
  13117. }
  13118. };
  13119. FreeCamera.prototype.dispose = function () {
  13120. this.inputs.clear();
  13121. _super.prototype.dispose.call(this);
  13122. };
  13123. FreeCamera.prototype.getTypeName = function () {
  13124. return "FreeCamera";
  13125. };
  13126. __decorate([
  13127. BABYLON.serializeAsVector3()
  13128. ], FreeCamera.prototype, "ellipsoid", void 0);
  13129. __decorate([
  13130. BABYLON.serialize()
  13131. ], FreeCamera.prototype, "checkCollisions", void 0);
  13132. __decorate([
  13133. BABYLON.serialize()
  13134. ], FreeCamera.prototype, "applyGravity", void 0);
  13135. return FreeCamera;
  13136. })(BABYLON.TargetCamera);
  13137. BABYLON.FreeCamera = FreeCamera;
  13138. })(BABYLON || (BABYLON = {}));
  13139. var BABYLON;
  13140. (function (BABYLON) {
  13141. var FreeCameraInputsManager = (function (_super) {
  13142. __extends(FreeCameraInputsManager, _super);
  13143. function FreeCameraInputsManager(camera) {
  13144. _super.call(this, camera);
  13145. }
  13146. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13147. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13148. return this;
  13149. };
  13150. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13151. if (touchEnabled === void 0) { touchEnabled = true; }
  13152. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13153. return this;
  13154. };
  13155. FreeCameraInputsManager.prototype.addGamepad = function () {
  13156. this.add(new BABYLON.FreeCameraGamepadInput());
  13157. return this;
  13158. };
  13159. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13160. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13161. return this;
  13162. };
  13163. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13164. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13165. return this;
  13166. };
  13167. FreeCameraInputsManager.prototype.addTouch = function () {
  13168. this.add(new BABYLON.FreeCameraTouchInput());
  13169. return this;
  13170. };
  13171. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13172. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13173. return this;
  13174. };
  13175. return FreeCameraInputsManager;
  13176. })(BABYLON.CameraInputsManager);
  13177. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13178. })(BABYLON || (BABYLON = {}));
  13179. var BABYLON;
  13180. (function (BABYLON) {
  13181. var FollowCamera = (function (_super) {
  13182. __extends(FollowCamera, _super);
  13183. function FollowCamera(name, position, scene, target) {
  13184. _super.call(this, name, position, scene);
  13185. this.radius = 12;
  13186. this.rotationOffset = 0;
  13187. this.heightOffset = 4;
  13188. this.cameraAcceleration = 0.05;
  13189. this.maxCameraSpeed = 20;
  13190. this.target = target;
  13191. }
  13192. FollowCamera.prototype.getRadians = function (degrees) {
  13193. return degrees * Math.PI / 180;
  13194. };
  13195. FollowCamera.prototype.follow = function (cameraTarget) {
  13196. if (!cameraTarget)
  13197. return;
  13198. var yRotation;
  13199. if (cameraTarget.rotationQuaternion) {
  13200. var rotMatrix = new BABYLON.Matrix();
  13201. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13202. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13203. }
  13204. else {
  13205. yRotation = cameraTarget.rotation.y;
  13206. }
  13207. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13208. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13209. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13210. var dx = targetX - this.position.x;
  13211. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13212. var dz = (targetZ) - this.position.z;
  13213. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13214. var vy = dy * this.cameraAcceleration;
  13215. var vz = dz * this.cameraAcceleration * 2;
  13216. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13217. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13218. }
  13219. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13220. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13221. }
  13222. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13223. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13224. }
  13225. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13226. this.setTarget(cameraTarget.position);
  13227. };
  13228. FollowCamera.prototype._checkInputs = function () {
  13229. _super.prototype._checkInputs.call(this);
  13230. this.follow(this.target);
  13231. };
  13232. FollowCamera.prototype.getTypeName = function () {
  13233. return "FollowCamera";
  13234. };
  13235. __decorate([
  13236. BABYLON.serialize()
  13237. ], FollowCamera.prototype, "radius", void 0);
  13238. __decorate([
  13239. BABYLON.serialize()
  13240. ], FollowCamera.prototype, "rotationOffset", void 0);
  13241. __decorate([
  13242. BABYLON.serialize()
  13243. ], FollowCamera.prototype, "heightOffset", void 0);
  13244. __decorate([
  13245. BABYLON.serialize()
  13246. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13247. __decorate([
  13248. BABYLON.serialize()
  13249. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13250. __decorate([
  13251. BABYLON.serializeAsMeshReference("lockedTargetId")
  13252. ], FollowCamera.prototype, "target", void 0);
  13253. return FollowCamera;
  13254. })(BABYLON.TargetCamera);
  13255. BABYLON.FollowCamera = FollowCamera;
  13256. var ArcFollowCamera = (function (_super) {
  13257. __extends(ArcFollowCamera, _super);
  13258. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13259. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13260. this.alpha = alpha;
  13261. this.beta = beta;
  13262. this.radius = radius;
  13263. this.target = target;
  13264. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13265. this.follow();
  13266. }
  13267. ArcFollowCamera.prototype.follow = function () {
  13268. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13269. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13270. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13271. this.position = this.target.position.add(this._cartesianCoordinates);
  13272. this.setTarget(this.target.position);
  13273. };
  13274. ArcFollowCamera.prototype._checkInputs = function () {
  13275. _super.prototype._checkInputs.call(this);
  13276. this.follow();
  13277. };
  13278. ArcFollowCamera.prototype.getTypeName = function () {
  13279. return "ArcFollowCamera";
  13280. };
  13281. return ArcFollowCamera;
  13282. })(BABYLON.TargetCamera);
  13283. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13284. })(BABYLON || (BABYLON = {}));
  13285. var BABYLON;
  13286. (function (BABYLON) {
  13287. // We're mainly based on the logic defined into the FreeCamera code
  13288. var TouchCamera = (function (_super) {
  13289. __extends(TouchCamera, _super);
  13290. //-- end properties for backward compatibility for inputs
  13291. function TouchCamera(name, position, scene) {
  13292. _super.call(this, name, position, scene);
  13293. this.inputs.addTouch();
  13294. this._setupInputs();
  13295. }
  13296. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13297. //-- Begin properties for backward compatibility for inputs
  13298. get: function () {
  13299. var touch = this.inputs.attached["touch"];
  13300. if (touch)
  13301. return touch.touchAngularSensibility;
  13302. },
  13303. set: function (value) {
  13304. var touch = this.inputs.attached["touch"];
  13305. if (touch)
  13306. touch.touchAngularSensibility = value;
  13307. },
  13308. enumerable: true,
  13309. configurable: true
  13310. });
  13311. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13312. get: function () {
  13313. var touch = this.inputs.attached["touch"];
  13314. if (touch)
  13315. return touch.touchMoveSensibility;
  13316. },
  13317. set: function (value) {
  13318. var touch = this.inputs.attached["touch"];
  13319. if (touch)
  13320. touch.touchMoveSensibility = value;
  13321. },
  13322. enumerable: true,
  13323. configurable: true
  13324. });
  13325. TouchCamera.prototype.getTypeName = function () {
  13326. return "TouchCamera";
  13327. };
  13328. TouchCamera.prototype._setupInputs = function () {
  13329. var mouse = this.inputs.attached["mouse"];
  13330. if (mouse) {
  13331. mouse.touchEnabled = false;
  13332. }
  13333. };
  13334. return TouchCamera;
  13335. })(BABYLON.FreeCamera);
  13336. BABYLON.TouchCamera = TouchCamera;
  13337. })(BABYLON || (BABYLON = {}));
  13338. var BABYLON;
  13339. (function (BABYLON) {
  13340. var ArcRotateCamera = (function (_super) {
  13341. __extends(ArcRotateCamera, _super);
  13342. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13343. var _this = this;
  13344. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13345. this.inertialAlphaOffset = 0;
  13346. this.inertialBetaOffset = 0;
  13347. this.inertialRadiusOffset = 0;
  13348. this.lowerAlphaLimit = null;
  13349. this.upperAlphaLimit = null;
  13350. this.lowerBetaLimit = 0.01;
  13351. this.upperBetaLimit = Math.PI;
  13352. this.lowerRadiusLimit = null;
  13353. this.upperRadiusLimit = null;
  13354. this.inertialPanningX = 0;
  13355. this.inertialPanningY = 0;
  13356. //-- end properties for backward compatibility for inputs
  13357. this.zoomOnFactor = 1;
  13358. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13359. this.allowUpsideDown = true;
  13360. this._viewMatrix = new BABYLON.Matrix();
  13361. // Panning
  13362. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13363. this.checkCollisions = false;
  13364. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13365. this._collider = new BABYLON.Collider();
  13366. this._previousPosition = BABYLON.Vector3.Zero();
  13367. this._collisionVelocity = BABYLON.Vector3.Zero();
  13368. this._newPosition = BABYLON.Vector3.Zero();
  13369. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13370. if (collidedMesh === void 0) { collidedMesh = null; }
  13371. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13372. newPosition.multiplyInPlace(_this._collider.radius);
  13373. }
  13374. if (!collidedMesh) {
  13375. _this._previousPosition.copyFrom(_this.position);
  13376. }
  13377. else {
  13378. _this.setPosition(newPosition);
  13379. if (_this.onCollide) {
  13380. _this.onCollide(collidedMesh);
  13381. }
  13382. }
  13383. // Recompute because of constraints
  13384. var cosa = Math.cos(_this.alpha);
  13385. var sina = Math.sin(_this.alpha);
  13386. var cosb = Math.cos(_this.beta);
  13387. var sinb = Math.sin(_this.beta);
  13388. if (sinb === 0) {
  13389. sinb = 0.0001;
  13390. }
  13391. var target = _this._getTargetPosition();
  13392. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13393. _this.position.copyFrom(_this._newPosition);
  13394. var up = _this.upVector;
  13395. if (_this.allowUpsideDown && _this.beta < 0) {
  13396. up = up.clone();
  13397. up = up.negate();
  13398. }
  13399. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13400. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13401. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13402. _this._collisionTriggered = false;
  13403. };
  13404. if (!target) {
  13405. this.target = BABYLON.Vector3.Zero();
  13406. }
  13407. else {
  13408. this.target = target;
  13409. }
  13410. this.alpha = alpha;
  13411. this.beta = beta;
  13412. this.radius = radius;
  13413. this.getViewMatrix();
  13414. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13415. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13416. }
  13417. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13418. //-- begin properties for backward compatibility for inputs
  13419. get: function () {
  13420. var pointers = this.inputs.attached["pointers"];
  13421. if (pointers)
  13422. return pointers.angularSensibilityX;
  13423. },
  13424. set: function (value) {
  13425. var pointers = this.inputs.attached["pointers"];
  13426. if (pointers) {
  13427. pointers.angularSensibilityX = value;
  13428. }
  13429. },
  13430. enumerable: true,
  13431. configurable: true
  13432. });
  13433. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13434. get: function () {
  13435. var pointers = this.inputs.attached["pointers"];
  13436. if (pointers)
  13437. return pointers.angularSensibilityY;
  13438. },
  13439. set: function (value) {
  13440. var pointers = this.inputs.attached["pointers"];
  13441. if (pointers) {
  13442. pointers.angularSensibilityY = value;
  13443. }
  13444. },
  13445. enumerable: true,
  13446. configurable: true
  13447. });
  13448. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13449. get: function () {
  13450. var pointers = this.inputs.attached["pointers"];
  13451. if (pointers)
  13452. return pointers.pinchPrecision;
  13453. },
  13454. set: function (value) {
  13455. var pointers = this.inputs.attached["pointers"];
  13456. if (pointers) {
  13457. pointers.pinchPrecision = value;
  13458. }
  13459. },
  13460. enumerable: true,
  13461. configurable: true
  13462. });
  13463. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13464. get: function () {
  13465. var pointers = this.inputs.attached["pointers"];
  13466. if (pointers)
  13467. return pointers.panningSensibility;
  13468. },
  13469. set: function (value) {
  13470. var pointers = this.inputs.attached["pointers"];
  13471. if (pointers) {
  13472. pointers.panningSensibility = value;
  13473. }
  13474. },
  13475. enumerable: true,
  13476. configurable: true
  13477. });
  13478. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13479. get: function () {
  13480. var keyboard = this.inputs.attached["keyboard"];
  13481. if (keyboard)
  13482. return keyboard.keysUp;
  13483. },
  13484. set: function (value) {
  13485. var keyboard = this.inputs.attached["keyboard"];
  13486. if (keyboard)
  13487. keyboard.keysUp = value;
  13488. },
  13489. enumerable: true,
  13490. configurable: true
  13491. });
  13492. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13493. get: function () {
  13494. var keyboard = this.inputs.attached["keyboard"];
  13495. if (keyboard)
  13496. return keyboard.keysDown;
  13497. },
  13498. set: function (value) {
  13499. var keyboard = this.inputs.attached["keyboard"];
  13500. if (keyboard)
  13501. keyboard.keysDown = value;
  13502. },
  13503. enumerable: true,
  13504. configurable: true
  13505. });
  13506. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13507. get: function () {
  13508. var keyboard = this.inputs.attached["keyboard"];
  13509. if (keyboard)
  13510. return keyboard.keysLeft;
  13511. },
  13512. set: function (value) {
  13513. var keyboard = this.inputs.attached["keyboard"];
  13514. if (keyboard)
  13515. keyboard.keysLeft = value;
  13516. },
  13517. enumerable: true,
  13518. configurable: true
  13519. });
  13520. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13521. get: function () {
  13522. var keyboard = this.inputs.attached["keyboard"];
  13523. if (keyboard)
  13524. return keyboard.keysRight;
  13525. },
  13526. set: function (value) {
  13527. var keyboard = this.inputs.attached["keyboard"];
  13528. if (keyboard)
  13529. keyboard.keysRight = value;
  13530. },
  13531. enumerable: true,
  13532. configurable: true
  13533. });
  13534. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13535. get: function () {
  13536. var mousewheel = this.inputs.attached["mousewheel"];
  13537. if (mousewheel)
  13538. return mousewheel.wheelPrecision;
  13539. },
  13540. set: function (value) {
  13541. var mousewheel = this.inputs.attached["mousewheel"];
  13542. if (mousewheel)
  13543. mousewheel.wheelPrecision = value;
  13544. },
  13545. enumerable: true,
  13546. configurable: true
  13547. });
  13548. // Cache
  13549. ArcRotateCamera.prototype._initCache = function () {
  13550. _super.prototype._initCache.call(this);
  13551. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13552. this._cache.alpha = undefined;
  13553. this._cache.beta = undefined;
  13554. this._cache.radius = undefined;
  13555. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13556. };
  13557. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13558. if (!ignoreParentClass) {
  13559. _super.prototype._updateCache.call(this);
  13560. }
  13561. this._cache.target.copyFrom(this._getTargetPosition());
  13562. this._cache.alpha = this.alpha;
  13563. this._cache.beta = this.beta;
  13564. this._cache.radius = this.radius;
  13565. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13566. };
  13567. ArcRotateCamera.prototype._getTargetPosition = function () {
  13568. if (this.target.getAbsolutePosition) {
  13569. return this.target.getAbsolutePosition();
  13570. }
  13571. return this.target;
  13572. };
  13573. // Synchronized
  13574. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13575. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13576. return false;
  13577. return this._cache.target.equals(this.target)
  13578. && this._cache.alpha === this.alpha
  13579. && this._cache.beta === this.beta
  13580. && this._cache.radius === this.radius
  13581. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13582. };
  13583. // Methods
  13584. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13585. var _this = this;
  13586. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13587. this._useCtrlForPanning = useCtrlForPanning;
  13588. this.inputs.attachElement(element, noPreventDefault);
  13589. this._reset = function () {
  13590. _this.inertialAlphaOffset = 0;
  13591. _this.inertialBetaOffset = 0;
  13592. _this.inertialRadiusOffset = 0;
  13593. };
  13594. };
  13595. ArcRotateCamera.prototype.detachControl = function (element) {
  13596. this.inputs.detachElement(element);
  13597. if (this._reset) {
  13598. this._reset();
  13599. }
  13600. };
  13601. ArcRotateCamera.prototype._checkInputs = function () {
  13602. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13603. if (this._collisionTriggered) {
  13604. return;
  13605. }
  13606. this.inputs.checkInputs();
  13607. // Inertia
  13608. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13609. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13610. this.beta += this.inertialBetaOffset;
  13611. this.radius -= this.inertialRadiusOffset;
  13612. this.inertialAlphaOffset *= this.inertia;
  13613. this.inertialBetaOffset *= this.inertia;
  13614. this.inertialRadiusOffset *= this.inertia;
  13615. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13616. this.inertialAlphaOffset = 0;
  13617. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13618. this.inertialBetaOffset = 0;
  13619. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13620. this.inertialRadiusOffset = 0;
  13621. }
  13622. // Panning inertia
  13623. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13624. if (!this._localDirection) {
  13625. this._localDirection = BABYLON.Vector3.Zero();
  13626. this._transformedDirection = BABYLON.Vector3.Zero();
  13627. }
  13628. this.inertialPanningX *= this.inertia;
  13629. this.inertialPanningY *= this.inertia;
  13630. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13631. this.inertialPanningX = 0;
  13632. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13633. this.inertialPanningY = 0;
  13634. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13635. this._localDirection.multiplyInPlace(this.panningAxis);
  13636. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13637. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13638. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13639. if (!this.panningAxis.y) {
  13640. this._transformedDirection.y = 0;
  13641. }
  13642. this.target.addInPlace(this._transformedDirection);
  13643. }
  13644. // Limits
  13645. this._checkLimits();
  13646. _super.prototype._checkInputs.call(this);
  13647. };
  13648. ArcRotateCamera.prototype._checkLimits = function () {
  13649. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13650. if (this.allowUpsideDown && this.beta > Math.PI) {
  13651. this.beta = this.beta - (2 * Math.PI);
  13652. }
  13653. }
  13654. else {
  13655. if (this.beta < this.lowerBetaLimit) {
  13656. this.beta = this.lowerBetaLimit;
  13657. }
  13658. }
  13659. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13660. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13661. this.beta = this.beta + (2 * Math.PI);
  13662. }
  13663. }
  13664. else {
  13665. if (this.beta > this.upperBetaLimit) {
  13666. this.beta = this.upperBetaLimit;
  13667. }
  13668. }
  13669. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13670. this.alpha = this.lowerAlphaLimit;
  13671. }
  13672. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13673. this.alpha = this.upperAlphaLimit;
  13674. }
  13675. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13676. this.radius = this.lowerRadiusLimit;
  13677. }
  13678. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13679. this.radius = this.upperRadiusLimit;
  13680. }
  13681. };
  13682. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13683. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13684. this.radius = radiusv3.length();
  13685. // Alpha
  13686. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13687. if (radiusv3.z < 0) {
  13688. this.alpha = 2 * Math.PI - this.alpha;
  13689. }
  13690. // Beta
  13691. this.beta = Math.acos(radiusv3.y / this.radius);
  13692. this._checkLimits();
  13693. };
  13694. ArcRotateCamera.prototype.setPosition = function (position) {
  13695. if (this.position.equals(position)) {
  13696. return;
  13697. }
  13698. this.position = position;
  13699. this.rebuildAnglesAndRadius();
  13700. };
  13701. ArcRotateCamera.prototype.setTarget = function (target) {
  13702. if (this._getTargetPosition().equals(target)) {
  13703. return;
  13704. }
  13705. this.target = target;
  13706. this.rebuildAnglesAndRadius();
  13707. };
  13708. ArcRotateCamera.prototype._getViewMatrix = function () {
  13709. // Compute
  13710. var cosa = Math.cos(this.alpha);
  13711. var sina = Math.sin(this.alpha);
  13712. var cosb = Math.cos(this.beta);
  13713. var sinb = Math.sin(this.beta);
  13714. if (sinb === 0) {
  13715. sinb = 0.0001;
  13716. }
  13717. var target = this._getTargetPosition();
  13718. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13719. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13720. this._collider.radius = this.collisionRadius;
  13721. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13722. this._collisionTriggered = true;
  13723. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13724. }
  13725. else {
  13726. this.position.copyFrom(this._newPosition);
  13727. var up = this.upVector;
  13728. if (this.allowUpsideDown && this.beta < 0) {
  13729. up = up.clone();
  13730. up = up.negate();
  13731. }
  13732. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13733. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13734. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13735. }
  13736. return this._viewMatrix;
  13737. };
  13738. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13739. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13740. meshes = meshes || this.getScene().meshes;
  13741. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13742. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13743. this.radius = distance * this.zoomOnFactor;
  13744. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13745. };
  13746. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13747. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13748. var meshesOrMinMaxVector;
  13749. var distance;
  13750. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13751. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13752. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13753. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13754. }
  13755. else {
  13756. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13757. distance = meshesOrMinMaxVectorAndDistance.distance;
  13758. }
  13759. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13760. if (!doNotUpdateMaxZ) {
  13761. this.maxZ = distance * 2;
  13762. }
  13763. };
  13764. /**
  13765. * @override
  13766. * Override Camera.createRigCamera
  13767. */
  13768. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13769. switch (this.cameraRigMode) {
  13770. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13771. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13772. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13773. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13774. case BABYLON.Camera.RIG_MODE_VR:
  13775. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13776. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13777. rigCam._cameraRigParams = {};
  13778. return rigCam;
  13779. }
  13780. return null;
  13781. };
  13782. /**
  13783. * @override
  13784. * Override Camera._updateRigCameras
  13785. */
  13786. ArcRotateCamera.prototype._updateRigCameras = function () {
  13787. switch (this.cameraRigMode) {
  13788. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13789. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13790. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13791. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13792. case BABYLON.Camera.RIG_MODE_VR:
  13793. var camLeft = this._rigCameras[0];
  13794. var camRight = this._rigCameras[1];
  13795. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13796. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13797. camLeft.beta = camRight.beta = this.beta;
  13798. camLeft.radius = camRight.radius = this.radius;
  13799. break;
  13800. }
  13801. _super.prototype._updateRigCameras.call(this);
  13802. };
  13803. ArcRotateCamera.prototype.dispose = function () {
  13804. this.inputs.clear();
  13805. _super.prototype.dispose.call(this);
  13806. };
  13807. ArcRotateCamera.prototype.getTypeName = function () {
  13808. return "ArcRotateCamera";
  13809. };
  13810. __decorate([
  13811. BABYLON.serialize()
  13812. ], ArcRotateCamera.prototype, "alpha", void 0);
  13813. __decorate([
  13814. BABYLON.serialize()
  13815. ], ArcRotateCamera.prototype, "beta", void 0);
  13816. __decorate([
  13817. BABYLON.serialize()
  13818. ], ArcRotateCamera.prototype, "radius", void 0);
  13819. __decorate([
  13820. BABYLON.serializeAsVector3()
  13821. ], ArcRotateCamera.prototype, "target", void 0);
  13822. __decorate([
  13823. BABYLON.serialize()
  13824. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13825. __decorate([
  13826. BABYLON.serialize()
  13827. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13828. __decorate([
  13829. BABYLON.serialize()
  13830. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13831. __decorate([
  13832. BABYLON.serialize()
  13833. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13834. __decorate([
  13835. BABYLON.serialize()
  13836. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13837. __decorate([
  13838. BABYLON.serialize()
  13839. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13840. __decorate([
  13841. BABYLON.serialize()
  13842. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13843. __decorate([
  13844. BABYLON.serialize()
  13845. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13846. __decorate([
  13847. BABYLON.serialize()
  13848. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13849. __decorate([
  13850. BABYLON.serialize()
  13851. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13852. __decorate([
  13853. BABYLON.serialize()
  13854. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13855. __decorate([
  13856. BABYLON.serialize()
  13857. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13858. __decorate([
  13859. BABYLON.serialize()
  13860. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13861. return ArcRotateCamera;
  13862. })(BABYLON.TargetCamera);
  13863. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13864. })(BABYLON || (BABYLON = {}));
  13865. var BABYLON;
  13866. (function (BABYLON) {
  13867. var ArcRotateCameraInputsManager = (function (_super) {
  13868. __extends(ArcRotateCameraInputsManager, _super);
  13869. function ArcRotateCameraInputsManager(camera) {
  13870. _super.call(this, camera);
  13871. }
  13872. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13873. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13874. return this;
  13875. };
  13876. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13877. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13878. return this;
  13879. };
  13880. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13881. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13882. return this;
  13883. };
  13884. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13885. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13886. return this;
  13887. };
  13888. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13889. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13890. return this;
  13891. };
  13892. return ArcRotateCameraInputsManager;
  13893. })(BABYLON.CameraInputsManager);
  13894. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13895. })(BABYLON || (BABYLON = {}));
  13896. var BABYLON;
  13897. (function (BABYLON) {
  13898. var RenderingManager = (function () {
  13899. function RenderingManager(scene) {
  13900. this._renderingGroups = new Array();
  13901. this._scene = scene;
  13902. }
  13903. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13904. if (this._scene._activeParticleSystems.length === 0) {
  13905. return;
  13906. }
  13907. // Particles
  13908. var activeCamera = this._scene.activeCamera;
  13909. var beforeParticlesDate = BABYLON.Tools.Now;
  13910. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13911. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13912. if (particleSystem.renderingGroupId !== index) {
  13913. continue;
  13914. }
  13915. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13916. continue;
  13917. }
  13918. this._clearDepthBuffer();
  13919. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13920. this._scene._activeParticles += particleSystem.render();
  13921. }
  13922. }
  13923. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13924. };
  13925. RenderingManager.prototype._renderSprites = function (index) {
  13926. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13927. return;
  13928. }
  13929. // Sprites
  13930. var activeCamera = this._scene.activeCamera;
  13931. var beforeSpritessDate = BABYLON.Tools.Now;
  13932. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13933. var spriteManager = this._scene.spriteManagers[id];
  13934. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13935. this._clearDepthBuffer();
  13936. spriteManager.render();
  13937. }
  13938. }
  13939. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13940. };
  13941. RenderingManager.prototype._clearDepthBuffer = function () {
  13942. if (this._depthBufferAlreadyCleaned) {
  13943. return;
  13944. }
  13945. this._scene.getEngine().clear(0, false, true);
  13946. this._depthBufferAlreadyCleaned = true;
  13947. };
  13948. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13949. if (this._currentRenderSprites) {
  13950. this._renderSprites(this._currentIndex);
  13951. }
  13952. if (this._currentRenderParticles) {
  13953. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13954. }
  13955. };
  13956. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13957. this._currentActiveMeshes = activeMeshes;
  13958. this._currentRenderParticles = renderParticles;
  13959. this._currentRenderSprites = renderSprites;
  13960. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13961. this._depthBufferAlreadyCleaned = index == 0;
  13962. var renderingGroup = this._renderingGroups[index];
  13963. var needToStepBack = false;
  13964. this._currentIndex = index;
  13965. if (renderingGroup) {
  13966. this._clearDepthBuffer();
  13967. if (!renderingGroup.onBeforeTransparentRendering) {
  13968. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13969. }
  13970. if (!renderingGroup.render(customRenderFunction)) {
  13971. this._renderingGroups.splice(index, 1);
  13972. needToStepBack = true;
  13973. this._renderSpritesAndParticles();
  13974. }
  13975. }
  13976. else {
  13977. this._renderSpritesAndParticles();
  13978. }
  13979. if (needToStepBack) {
  13980. index--;
  13981. }
  13982. }
  13983. };
  13984. RenderingManager.prototype.reset = function () {
  13985. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13986. if (renderingGroup) {
  13987. renderingGroup.prepare();
  13988. }
  13989. });
  13990. };
  13991. RenderingManager.prototype.dispatch = function (subMesh) {
  13992. var mesh = subMesh.getMesh();
  13993. var renderingGroupId = mesh.renderingGroupId || 0;
  13994. if (!this._renderingGroups[renderingGroupId]) {
  13995. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13996. }
  13997. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13998. };
  13999. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14000. return RenderingManager;
  14001. })();
  14002. BABYLON.RenderingManager = RenderingManager;
  14003. })(BABYLON || (BABYLON = {}));
  14004. var BABYLON;
  14005. (function (BABYLON) {
  14006. var RenderingGroup = (function () {
  14007. function RenderingGroup(index, scene) {
  14008. this.index = index;
  14009. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14010. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14011. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14012. this._scene = scene;
  14013. }
  14014. RenderingGroup.prototype.render = function (customRenderFunction) {
  14015. if (customRenderFunction) {
  14016. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14017. return true;
  14018. }
  14019. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  14020. if (this.onBeforeTransparentRendering) {
  14021. this.onBeforeTransparentRendering();
  14022. }
  14023. return false;
  14024. }
  14025. var engine = this._scene.getEngine();
  14026. // Opaque
  14027. var subIndex;
  14028. var submesh;
  14029. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  14030. submesh = this._opaqueSubMeshes.data[subIndex];
  14031. submesh.render(false);
  14032. }
  14033. // Alpha test
  14034. engine.setAlphaTesting(true);
  14035. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  14036. submesh = this._alphaTestSubMeshes.data[subIndex];
  14037. submesh.render(false);
  14038. }
  14039. engine.setAlphaTesting(false);
  14040. if (this.onBeforeTransparentRendering) {
  14041. this.onBeforeTransparentRendering();
  14042. }
  14043. // Transparent
  14044. if (this._transparentSubMeshes.length) {
  14045. // Sorting
  14046. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  14047. submesh = this._transparentSubMeshes.data[subIndex];
  14048. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  14049. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  14050. }
  14051. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  14052. sortedArray.sort(function (a, b) {
  14053. // Alpha index first
  14054. if (a._alphaIndex > b._alphaIndex) {
  14055. return 1;
  14056. }
  14057. if (a._alphaIndex < b._alphaIndex) {
  14058. return -1;
  14059. }
  14060. // Then distance to camera
  14061. if (a._distanceToCamera < b._distanceToCamera) {
  14062. return 1;
  14063. }
  14064. if (a._distanceToCamera > b._distanceToCamera) {
  14065. return -1;
  14066. }
  14067. return 0;
  14068. });
  14069. // Rendering
  14070. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14071. submesh = sortedArray[subIndex];
  14072. submesh.render(true);
  14073. }
  14074. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14075. }
  14076. return true;
  14077. };
  14078. RenderingGroup.prototype.prepare = function () {
  14079. this._opaqueSubMeshes.reset();
  14080. this._transparentSubMeshes.reset();
  14081. this._alphaTestSubMeshes.reset();
  14082. };
  14083. RenderingGroup.prototype.dispatch = function (subMesh) {
  14084. var material = subMesh.getMaterial();
  14085. var mesh = subMesh.getMesh();
  14086. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14087. this._transparentSubMeshes.push(subMesh);
  14088. }
  14089. else if (material.needAlphaTesting()) {
  14090. this._alphaTestSubMeshes.push(subMesh);
  14091. }
  14092. else {
  14093. this._opaqueSubMeshes.push(subMesh); // Opaque
  14094. }
  14095. };
  14096. return RenderingGroup;
  14097. })();
  14098. BABYLON.RenderingGroup = RenderingGroup;
  14099. })(BABYLON || (BABYLON = {}));
  14100. var BABYLON;
  14101. (function (BABYLON) {
  14102. var PointerEventTypes = (function () {
  14103. function PointerEventTypes() {
  14104. }
  14105. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14106. get: function () {
  14107. return PointerEventTypes._POINTERDOWN;
  14108. },
  14109. enumerable: true,
  14110. configurable: true
  14111. });
  14112. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14113. get: function () {
  14114. return PointerEventTypes._POINTERUP;
  14115. },
  14116. enumerable: true,
  14117. configurable: true
  14118. });
  14119. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14120. get: function () {
  14121. return PointerEventTypes._POINTERMOVE;
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14127. get: function () {
  14128. return PointerEventTypes._POINTERWHEEL;
  14129. },
  14130. enumerable: true,
  14131. configurable: true
  14132. });
  14133. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14134. get: function () {
  14135. return PointerEventTypes._POINTERPICK;
  14136. },
  14137. enumerable: true,
  14138. configurable: true
  14139. });
  14140. PointerEventTypes._POINTERDOWN = 0x01;
  14141. PointerEventTypes._POINTERUP = 0x02;
  14142. PointerEventTypes._POINTERMOVE = 0x04;
  14143. PointerEventTypes._POINTERWHEEL = 0x08;
  14144. PointerEventTypes._POINTERPICK = 0x10;
  14145. return PointerEventTypes;
  14146. })();
  14147. BABYLON.PointerEventTypes = PointerEventTypes;
  14148. /**
  14149. * This type contains all the data related to a pointer event in Babylon.js.
  14150. * 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.
  14151. */
  14152. var PointerInfo = (function () {
  14153. function PointerInfo(type, event, pickInfo) {
  14154. this.type = type;
  14155. this.event = event;
  14156. this.pickInfo = pickInfo;
  14157. }
  14158. return PointerInfo;
  14159. })();
  14160. BABYLON.PointerInfo = PointerInfo;
  14161. /**
  14162. * Represents a scene to be rendered by the engine.
  14163. * @see http://doc.babylonjs.com/page.php?p=21911
  14164. */
  14165. var Scene = (function () {
  14166. /**
  14167. * @constructor
  14168. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14169. */
  14170. function Scene(engine) {
  14171. // Members
  14172. this.autoClear = true;
  14173. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14174. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14175. this.forceWireframe = false;
  14176. this.forcePointsCloud = false;
  14177. this.forceShowBoundingBoxes = false;
  14178. this.animationsEnabled = true;
  14179. this.constantlyUpdateMeshUnderPointer = false;
  14180. // Events
  14181. /**
  14182. * An event triggered when the scene is disposed.
  14183. * @type {BABYLON.Observable}
  14184. */
  14185. this.onDisposeObservable = new BABYLON.Observable();
  14186. /**
  14187. * An event triggered before rendering the scene
  14188. * @type {BABYLON.Observable}
  14189. */
  14190. this.onBeforeRenderObservable = new BABYLON.Observable();
  14191. /**
  14192. * An event triggered after rendering the scene
  14193. * @type {BABYLON.Observable}
  14194. */
  14195. this.onAfterRenderObservable = new BABYLON.Observable();
  14196. /**
  14197. * An event triggered when the scene is ready
  14198. * @type {BABYLON.Observable}
  14199. */
  14200. this.onReadyObservable = new BABYLON.Observable();
  14201. /**
  14202. * An event triggered before rendering a camera
  14203. * @type {BABYLON.Observable}
  14204. */
  14205. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14206. /**
  14207. * An event triggered after rendering a camera
  14208. * @type {BABYLON.Observable}
  14209. */
  14210. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14211. /**
  14212. * An event triggered when a camera is created
  14213. * @type {BABYLON.Observable}
  14214. */
  14215. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14216. /**
  14217. * An event triggered when a camera is removed
  14218. * @type {BABYLON.Observable}
  14219. */
  14220. this.onCameraRemovedObservable = new BABYLON.Observable();
  14221. /**
  14222. * An event triggered when a light is created
  14223. * @type {BABYLON.Observable}
  14224. */
  14225. this.onNewLightAddedObservable = new BABYLON.Observable();
  14226. /**
  14227. * An event triggered when a light is removed
  14228. * @type {BABYLON.Observable}
  14229. */
  14230. this.onLightRemovedObservable = new BABYLON.Observable();
  14231. /**
  14232. * An event triggered when a geometry is created
  14233. * @type {BABYLON.Observable}
  14234. */
  14235. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14236. /**
  14237. * An event triggered when a geometry is removed
  14238. * @type {BABYLON.Observable}
  14239. */
  14240. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14241. /**
  14242. * An event triggered when a mesh is created
  14243. * @type {BABYLON.Observable}
  14244. */
  14245. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14246. /**
  14247. * An event triggered when a mesh is removed
  14248. * @type {BABYLON.Observable}
  14249. */
  14250. this.onMeshRemovedObservable = new BABYLON.Observable();
  14251. // Animations
  14252. this.animations = [];
  14253. /**
  14254. * Observable event triggered each time an input event is received from the rendering canvas
  14255. */
  14256. this.onPointerObservable = new BABYLON.Observable();
  14257. 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
  14258. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14259. this._startingPointerTime = 0;
  14260. // Fog
  14261. /**
  14262. * is fog enabled on this scene.
  14263. * @type {boolean}
  14264. */
  14265. this.fogEnabled = true;
  14266. this.fogMode = Scene.FOGMODE_NONE;
  14267. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14268. this.fogDensity = 0.1;
  14269. this.fogStart = 0;
  14270. this.fogEnd = 1000.0;
  14271. // Lights
  14272. /**
  14273. * is shadow enabled on this scene.
  14274. * @type {boolean}
  14275. */
  14276. this.shadowsEnabled = true;
  14277. /**
  14278. * is light enabled on this scene.
  14279. * @type {boolean}
  14280. */
  14281. this.lightsEnabled = true;
  14282. /**
  14283. * All of the lights added to this scene.
  14284. * @see BABYLON.Light
  14285. * @type {BABYLON.Light[]}
  14286. */
  14287. this.lights = new Array();
  14288. // Cameras
  14289. /**
  14290. * All of the cameras added to this scene.
  14291. * @see BABYLON.Camera
  14292. * @type {BABYLON.Camera[]}
  14293. */
  14294. this.cameras = new Array();
  14295. this.activeCameras = new Array();
  14296. // Meshes
  14297. /**
  14298. * All of the (abstract) meshes added to this scene.
  14299. * @see BABYLON.AbstractMesh
  14300. * @type {BABYLON.AbstractMesh[]}
  14301. */
  14302. this.meshes = new Array();
  14303. // Geometries
  14304. this._geometries = new Array();
  14305. this.materials = new Array();
  14306. this.multiMaterials = new Array();
  14307. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14308. // Textures
  14309. this.texturesEnabled = true;
  14310. this.textures = new Array();
  14311. // Particles
  14312. this.particlesEnabled = true;
  14313. this.particleSystems = new Array();
  14314. // Sprites
  14315. this.spritesEnabled = true;
  14316. this.spriteManagers = new Array();
  14317. // Layers
  14318. this.layers = new Array();
  14319. // Skeletons
  14320. this.skeletonsEnabled = true;
  14321. this.skeletons = new Array();
  14322. // Lens flares
  14323. this.lensFlaresEnabled = true;
  14324. this.lensFlareSystems = new Array();
  14325. // Collisions
  14326. this.collisionsEnabled = true;
  14327. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14328. // Postprocesses
  14329. this.postProcessesEnabled = true;
  14330. // Customs render targets
  14331. this.renderTargetsEnabled = true;
  14332. this.dumpNextRenderTargets = false;
  14333. this.customRenderTargets = new Array();
  14334. // Imported meshes
  14335. this.importedMeshesFiles = new Array();
  14336. // Probes
  14337. this.probesEnabled = true;
  14338. this.reflectionProbes = new Array();
  14339. this._actionManagers = new Array();
  14340. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14341. // Procedural textures
  14342. this.proceduralTexturesEnabled = true;
  14343. this._proceduralTextures = new Array();
  14344. this.soundTracks = new Array();
  14345. this._audioEnabled = true;
  14346. this._headphone = false;
  14347. this._totalVertices = 0;
  14348. this._activeIndices = 0;
  14349. this._activeParticles = 0;
  14350. this._lastFrameDuration = 0;
  14351. this._evaluateActiveMeshesDuration = 0;
  14352. this._renderTargetsDuration = 0;
  14353. this._particlesDuration = 0;
  14354. this._renderDuration = 0;
  14355. this._spritesDuration = 0;
  14356. this._animationRatio = 0;
  14357. this._renderId = 0;
  14358. this._executeWhenReadyTimeoutId = -1;
  14359. this._intermediateRendering = false;
  14360. this._toBeDisposed = new BABYLON.SmartArray(256);
  14361. this._pendingData = []; //ANY
  14362. this._activeMeshes = new BABYLON.SmartArray(256);
  14363. this._processedMaterials = new BABYLON.SmartArray(256);
  14364. this._renderTargets = new BABYLON.SmartArray(256);
  14365. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14366. this._activeSkeletons = new BABYLON.SmartArray(32);
  14367. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14368. this._activeBones = 0;
  14369. this._activeAnimatables = new Array();
  14370. this._transformMatrix = BABYLON.Matrix.Zero();
  14371. this._edgesRenderers = new BABYLON.SmartArray(16);
  14372. this._uniqueIdCounter = 0;
  14373. this._engine = engine;
  14374. engine.scenes.push(this);
  14375. this._renderingManager = new BABYLON.RenderingManager(this);
  14376. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14377. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14378. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14379. if (BABYLON.OutlineRenderer) {
  14380. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14381. }
  14382. this.attachControl();
  14383. this._debugLayer = new BABYLON.DebugLayer(this);
  14384. if (BABYLON.SoundTrack) {
  14385. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14386. }
  14387. //simplification queue
  14388. if (BABYLON.SimplificationQueue) {
  14389. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14390. }
  14391. //collision coordinator initialization. For now legacy per default.
  14392. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14393. }
  14394. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14395. get: function () {
  14396. return Scene._FOGMODE_NONE;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14402. get: function () {
  14403. return Scene._FOGMODE_EXP;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14409. get: function () {
  14410. return Scene._FOGMODE_EXP2;
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14416. get: function () {
  14417. return Scene._FOGMODE_LINEAR;
  14418. },
  14419. enumerable: true,
  14420. configurable: true
  14421. });
  14422. Object.defineProperty(Scene.prototype, "onDispose", {
  14423. set: function (callback) {
  14424. if (this._onDisposeObserver) {
  14425. this.onDisposeObservable.remove(this._onDisposeObserver);
  14426. }
  14427. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14428. },
  14429. enumerable: true,
  14430. configurable: true
  14431. });
  14432. Object.defineProperty(Scene.prototype, "beforeRender", {
  14433. set: function (callback) {
  14434. if (this._onBeforeRenderObserver) {
  14435. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14436. }
  14437. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14438. },
  14439. enumerable: true,
  14440. configurable: true
  14441. });
  14442. Object.defineProperty(Scene.prototype, "afterRender", {
  14443. set: function (callback) {
  14444. if (this._onAfterRenderObserver) {
  14445. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14446. }
  14447. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14448. },
  14449. enumerable: true,
  14450. configurable: true
  14451. });
  14452. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14453. set: function (callback) {
  14454. if (this._onBeforeCameraRenderObserver) {
  14455. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14456. }
  14457. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14458. },
  14459. enumerable: true,
  14460. configurable: true
  14461. });
  14462. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14463. set: function (callback) {
  14464. if (this._onAfterCameraRenderObserver) {
  14465. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14466. }
  14467. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14468. },
  14469. enumerable: true,
  14470. configurable: true
  14471. });
  14472. Object.defineProperty(Scene.prototype, "debugLayer", {
  14473. // Properties
  14474. get: function () {
  14475. return this._debugLayer;
  14476. },
  14477. enumerable: true,
  14478. configurable: true
  14479. });
  14480. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14481. get: function () {
  14482. return this._workerCollisions;
  14483. },
  14484. set: function (enabled) {
  14485. enabled = (enabled && !!Worker);
  14486. this._workerCollisions = enabled;
  14487. if (this.collisionCoordinator) {
  14488. this.collisionCoordinator.destroy();
  14489. }
  14490. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14491. this.collisionCoordinator.init(this);
  14492. },
  14493. enumerable: true,
  14494. configurable: true
  14495. });
  14496. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14497. get: function () {
  14498. return this._selectionOctree;
  14499. },
  14500. enumerable: true,
  14501. configurable: true
  14502. });
  14503. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14504. /**
  14505. * The mesh that is currently under the pointer.
  14506. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14507. */
  14508. get: function () {
  14509. return this._pointerOverMesh;
  14510. },
  14511. enumerable: true,
  14512. configurable: true
  14513. });
  14514. Object.defineProperty(Scene.prototype, "pointerX", {
  14515. /**
  14516. * Current on-screen X position of the pointer
  14517. * @return {number} X position of the pointer
  14518. */
  14519. get: function () {
  14520. return this._pointerX;
  14521. },
  14522. enumerable: true,
  14523. configurable: true
  14524. });
  14525. Object.defineProperty(Scene.prototype, "pointerY", {
  14526. /**
  14527. * Current on-screen Y position of the pointer
  14528. * @return {number} Y position of the pointer
  14529. */
  14530. get: function () {
  14531. return this._pointerY;
  14532. },
  14533. enumerable: true,
  14534. configurable: true
  14535. });
  14536. Scene.prototype.getCachedMaterial = function () {
  14537. return this._cachedMaterial;
  14538. };
  14539. Scene.prototype.getBoundingBoxRenderer = function () {
  14540. return this._boundingBoxRenderer;
  14541. };
  14542. Scene.prototype.getOutlineRenderer = function () {
  14543. return this._outlineRenderer;
  14544. };
  14545. Scene.prototype.getEngine = function () {
  14546. return this._engine;
  14547. };
  14548. Scene.prototype.getTotalVertices = function () {
  14549. return this._totalVertices;
  14550. };
  14551. Scene.prototype.getActiveIndices = function () {
  14552. return this._activeIndices;
  14553. };
  14554. Scene.prototype.getActiveParticles = function () {
  14555. return this._activeParticles;
  14556. };
  14557. Scene.prototype.getActiveBones = function () {
  14558. return this._activeBones;
  14559. };
  14560. // Stats
  14561. Scene.prototype.getLastFrameDuration = function () {
  14562. return this._lastFrameDuration;
  14563. };
  14564. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14565. return this._evaluateActiveMeshesDuration;
  14566. };
  14567. Scene.prototype.getActiveMeshes = function () {
  14568. return this._activeMeshes;
  14569. };
  14570. Scene.prototype.getRenderTargetsDuration = function () {
  14571. return this._renderTargetsDuration;
  14572. };
  14573. Scene.prototype.getRenderDuration = function () {
  14574. return this._renderDuration;
  14575. };
  14576. Scene.prototype.getParticlesDuration = function () {
  14577. return this._particlesDuration;
  14578. };
  14579. Scene.prototype.getSpritesDuration = function () {
  14580. return this._spritesDuration;
  14581. };
  14582. Scene.prototype.getAnimationRatio = function () {
  14583. return this._animationRatio;
  14584. };
  14585. Scene.prototype.getRenderId = function () {
  14586. return this._renderId;
  14587. };
  14588. Scene.prototype.incrementRenderId = function () {
  14589. this._renderId++;
  14590. };
  14591. Scene.prototype._updatePointerPosition = function (evt) {
  14592. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14593. this._pointerX = evt.clientX - canvasRect.left;
  14594. this._pointerY = evt.clientY - canvasRect.top;
  14595. this._unTranslatedPointerX = this._pointerX;
  14596. this._unTranslatedPointerY = this._pointerY;
  14597. if (this.cameraToUseForPointers) {
  14598. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14599. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14600. }
  14601. };
  14602. // Pointers handling
  14603. /**
  14604. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14605. * @param attachUp defines if you want to attach events to pointerup
  14606. * @param attachDown defines if you want to attach events to pointerdown
  14607. * @param attachMove defines if you want to attach events to pointermove
  14608. */
  14609. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14610. var _this = this;
  14611. if (attachUp === void 0) { attachUp = true; }
  14612. if (attachDown === void 0) { attachDown = true; }
  14613. if (attachMove === void 0) { attachMove = true; }
  14614. var spritePredicate = function (sprite) {
  14615. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14616. };
  14617. this._onPointerMove = function (evt) {
  14618. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14619. return;
  14620. }
  14621. var canvas = _this._engine.getRenderingCanvas();
  14622. _this._updatePointerPosition(evt);
  14623. if (!_this.pointerMovePredicate) {
  14624. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14625. }
  14626. // Meshes
  14627. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14628. if (pickResult.hit && pickResult.pickedMesh) {
  14629. _this.setPointerOverSprite(null);
  14630. _this.setPointerOverMesh(pickResult.pickedMesh);
  14631. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14632. canvas.style.cursor = "pointer";
  14633. }
  14634. else {
  14635. canvas.style.cursor = "";
  14636. }
  14637. }
  14638. else {
  14639. _this.setPointerOverMesh(null);
  14640. // Sprites
  14641. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14642. if (pickResult.hit && pickResult.pickedSprite) {
  14643. canvas.style.cursor = "pointer";
  14644. _this.setPointerOverSprite(pickResult.pickedSprite);
  14645. }
  14646. else {
  14647. _this.setPointerOverSprite(null);
  14648. // Restore pointer
  14649. canvas.style.cursor = "";
  14650. }
  14651. }
  14652. if (_this.onPointerMove) {
  14653. _this.onPointerMove(evt, pickResult);
  14654. }
  14655. if (_this.onPointerObservable.hasObservers()) {
  14656. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14657. var pi = new PointerInfo(type, evt, pickResult);
  14658. _this.onPointerObservable.notifyObservers(pi, type);
  14659. }
  14660. };
  14661. this._onPointerDown = function (evt) {
  14662. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14663. return;
  14664. }
  14665. _this._updatePointerPosition(evt);
  14666. _this._startingPointerPosition.x = _this._pointerX;
  14667. _this._startingPointerPosition.y = _this._pointerY;
  14668. _this._startingPointerTime = new Date().getTime();
  14669. if (!_this.pointerDownPredicate) {
  14670. _this.pointerDownPredicate = function (mesh) {
  14671. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14672. };
  14673. }
  14674. // Meshes
  14675. _this._pickedDownMesh = null;
  14676. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14677. if (pickResult.hit && pickResult.pickedMesh) {
  14678. if (pickResult.pickedMesh.actionManager) {
  14679. _this._pickedDownMesh = pickResult.pickedMesh;
  14680. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14681. switch (evt.button) {
  14682. case 0:
  14683. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14684. break;
  14685. case 1:
  14686. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14687. break;
  14688. case 2:
  14689. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14690. break;
  14691. }
  14692. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14693. }
  14694. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14695. var that = _this;
  14696. window.setTimeout(function () {
  14697. 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);
  14698. if (pickResult.hit && pickResult.pickedMesh) {
  14699. if (pickResult.pickedMesh.actionManager) {
  14700. 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)) {
  14701. that._startingPointerTime = 0;
  14702. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14703. }
  14704. }
  14705. }
  14706. }, BABYLON.ActionManager.LongPressDelay);
  14707. }
  14708. }
  14709. }
  14710. if (_this.onPointerDown) {
  14711. _this.onPointerDown(evt, pickResult);
  14712. }
  14713. if (_this.onPointerObservable.hasObservers()) {
  14714. var type = PointerEventTypes.POINTERDOWN;
  14715. var pi = new PointerInfo(type, evt, pickResult);
  14716. _this.onPointerObservable.notifyObservers(pi, type);
  14717. }
  14718. // Sprites
  14719. _this._pickedDownSprite = null;
  14720. if (_this.spriteManagers.length > 0) {
  14721. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14722. if (pickResult.hit && pickResult.pickedSprite) {
  14723. if (pickResult.pickedSprite.actionManager) {
  14724. _this._pickedDownSprite = pickResult.pickedSprite;
  14725. switch (evt.button) {
  14726. case 0:
  14727. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14728. break;
  14729. case 1:
  14730. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14731. break;
  14732. case 2:
  14733. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14734. break;
  14735. }
  14736. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14737. }
  14738. }
  14739. }
  14740. };
  14741. this._onPointerUp = function (evt) {
  14742. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14743. return;
  14744. }
  14745. _this._updatePointerPosition(evt);
  14746. if (!_this.pointerUpPredicate) {
  14747. _this.pointerUpPredicate = function (mesh) {
  14748. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14749. };
  14750. }
  14751. // Meshes
  14752. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14753. if (pickResult.hit && pickResult.pickedMesh) {
  14754. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14755. if (_this.onPointerPick) {
  14756. _this.onPointerPick(evt, pickResult);
  14757. }
  14758. if (_this.onPointerObservable.hasObservers()) {
  14759. var type = PointerEventTypes.POINTERPICK;
  14760. var pi = new PointerInfo(type, evt, pickResult);
  14761. _this.onPointerObservable.notifyObservers(pi, type);
  14762. }
  14763. }
  14764. if (pickResult.pickedMesh.actionManager) {
  14765. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14766. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14767. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14768. }
  14769. }
  14770. }
  14771. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14772. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14773. }
  14774. if (_this.onPointerUp) {
  14775. _this.onPointerUp(evt, pickResult);
  14776. }
  14777. if (_this.onPointerObservable.hasObservers()) {
  14778. var type = PointerEventTypes.POINTERUP;
  14779. var pi = new PointerInfo(type, evt, pickResult);
  14780. _this.onPointerObservable.notifyObservers(pi, type);
  14781. }
  14782. _this._startingPointerTime = 0;
  14783. // Sprites
  14784. if (_this.spriteManagers.length > 0) {
  14785. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14786. if (pickResult.hit && pickResult.pickedSprite) {
  14787. if (pickResult.pickedSprite.actionManager) {
  14788. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14789. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14790. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14791. }
  14792. }
  14793. }
  14794. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14795. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14796. }
  14797. }
  14798. };
  14799. this._onKeyDown = function (evt) {
  14800. if (_this.actionManager) {
  14801. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14802. }
  14803. };
  14804. this._onKeyUp = function (evt) {
  14805. if (_this.actionManager) {
  14806. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14807. }
  14808. };
  14809. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14810. if (attachMove) {
  14811. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14812. // Wheel
  14813. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14814. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14815. }
  14816. if (attachDown) {
  14817. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14818. }
  14819. if (attachUp) {
  14820. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14821. }
  14822. BABYLON.Tools.RegisterTopRootEvents([
  14823. { name: "keydown", handler: this._onKeyDown },
  14824. { name: "keyup", handler: this._onKeyUp }
  14825. ]);
  14826. };
  14827. Scene.prototype.detachControl = function () {
  14828. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14829. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14830. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14831. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14832. // Wheel
  14833. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14834. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14835. BABYLON.Tools.UnregisterTopRootEvents([
  14836. { name: "keydown", handler: this._onKeyDown },
  14837. { name: "keyup", handler: this._onKeyUp }
  14838. ]);
  14839. };
  14840. // Ready
  14841. Scene.prototype.isReady = function () {
  14842. if (this._pendingData.length > 0) {
  14843. return false;
  14844. }
  14845. var index;
  14846. for (index = 0; index < this._geometries.length; index++) {
  14847. var geometry = this._geometries[index];
  14848. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14849. return false;
  14850. }
  14851. }
  14852. for (index = 0; index < this.meshes.length; index++) {
  14853. var mesh = this.meshes[index];
  14854. if (!mesh.isReady()) {
  14855. return false;
  14856. }
  14857. var mat = mesh.material;
  14858. if (mat) {
  14859. if (!mat.isReady(mesh)) {
  14860. return false;
  14861. }
  14862. }
  14863. }
  14864. return true;
  14865. };
  14866. Scene.prototype.resetCachedMaterial = function () {
  14867. this._cachedMaterial = null;
  14868. };
  14869. Scene.prototype.registerBeforeRender = function (func) {
  14870. this.onBeforeRenderObservable.add(func);
  14871. };
  14872. Scene.prototype.unregisterBeforeRender = function (func) {
  14873. this.onBeforeRenderObservable.removeCallback(func);
  14874. };
  14875. Scene.prototype.registerAfterRender = function (func) {
  14876. this.onAfterRenderObservable.add(func);
  14877. };
  14878. Scene.prototype.unregisterAfterRender = function (func) {
  14879. this.onAfterRenderObservable.removeCallback(func);
  14880. };
  14881. Scene.prototype._addPendingData = function (data) {
  14882. this._pendingData.push(data);
  14883. };
  14884. Scene.prototype._removePendingData = function (data) {
  14885. var index = this._pendingData.indexOf(data);
  14886. if (index !== -1) {
  14887. this._pendingData.splice(index, 1);
  14888. }
  14889. };
  14890. Scene.prototype.getWaitingItemsCount = function () {
  14891. return this._pendingData.length;
  14892. };
  14893. /**
  14894. * Registers a function to be executed when the scene is ready.
  14895. * @param {Function} func - the function to be executed.
  14896. */
  14897. Scene.prototype.executeWhenReady = function (func) {
  14898. var _this = this;
  14899. this.onReadyObservable.add(func);
  14900. if (this._executeWhenReadyTimeoutId !== -1) {
  14901. return;
  14902. }
  14903. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14904. _this._checkIsReady();
  14905. }, 150);
  14906. };
  14907. Scene.prototype._checkIsReady = function () {
  14908. var _this = this;
  14909. if (this.isReady()) {
  14910. this.onReadyObservable.notifyObservers(this);
  14911. this.onReadyObservable.clear();
  14912. this._executeWhenReadyTimeoutId = -1;
  14913. return;
  14914. }
  14915. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14916. _this._checkIsReady();
  14917. }, 150);
  14918. };
  14919. // Animations
  14920. /**
  14921. * Will start the animation sequence of a given target
  14922. * @param target - the target
  14923. * @param {number} from - from which frame should animation start
  14924. * @param {number} to - till which frame should animation run.
  14925. * @param {boolean} [loop] - should the animation loop
  14926. * @param {number} [speedRatio] - the speed in which to run the animation
  14927. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14928. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14929. * @return {BABYLON.Animatable} the animatable object created for this animation
  14930. * @see BABYLON.Animatable
  14931. * @see http://doc.babylonjs.com/page.php?p=22081
  14932. */
  14933. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14934. if (speedRatio === void 0) { speedRatio = 1.0; }
  14935. this.stopAnimation(target);
  14936. if (!animatable) {
  14937. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14938. }
  14939. // Local animations
  14940. if (target.animations) {
  14941. animatable.appendAnimations(target, target.animations);
  14942. }
  14943. // Children animations
  14944. if (target.getAnimatables) {
  14945. var animatables = target.getAnimatables();
  14946. for (var index = 0; index < animatables.length; index++) {
  14947. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14948. }
  14949. }
  14950. animatable.reset();
  14951. return animatable;
  14952. };
  14953. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14954. if (speedRatio === undefined) {
  14955. speedRatio = 1.0;
  14956. }
  14957. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14958. return animatable;
  14959. };
  14960. Scene.prototype.getAnimatableByTarget = function (target) {
  14961. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14962. if (this._activeAnimatables[index].target === target) {
  14963. return this._activeAnimatables[index];
  14964. }
  14965. }
  14966. return null;
  14967. };
  14968. Object.defineProperty(Scene.prototype, "Animatables", {
  14969. get: function () {
  14970. return this._activeAnimatables;
  14971. },
  14972. enumerable: true,
  14973. configurable: true
  14974. });
  14975. /**
  14976. * Will stop the animation of the given target
  14977. * @param target - the target
  14978. * @see beginAnimation
  14979. */
  14980. Scene.prototype.stopAnimation = function (target) {
  14981. var animatable = this.getAnimatableByTarget(target);
  14982. if (animatable) {
  14983. animatable.stop();
  14984. }
  14985. };
  14986. Scene.prototype._animate = function () {
  14987. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14988. return;
  14989. }
  14990. if (!this._animationStartDate) {
  14991. if (this._pendingData.length > 0) {
  14992. return;
  14993. }
  14994. this._animationStartDate = BABYLON.Tools.Now;
  14995. }
  14996. // Getting time
  14997. var now = BABYLON.Tools.Now;
  14998. var delay = now - this._animationStartDate;
  14999. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15000. this._activeAnimatables[index]._animate(delay);
  15001. }
  15002. };
  15003. // Matrix
  15004. Scene.prototype.getViewMatrix = function () {
  15005. return this._viewMatrix;
  15006. };
  15007. Scene.prototype.getProjectionMatrix = function () {
  15008. return this._projectionMatrix;
  15009. };
  15010. Scene.prototype.getTransformMatrix = function () {
  15011. return this._transformMatrix;
  15012. };
  15013. Scene.prototype.setTransformMatrix = function (view, projection) {
  15014. this._viewMatrix = view;
  15015. this._projectionMatrix = projection;
  15016. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15017. };
  15018. // Methods
  15019. Scene.prototype.addMesh = function (newMesh) {
  15020. newMesh.uniqueId = this._uniqueIdCounter++;
  15021. var position = this.meshes.push(newMesh);
  15022. //notify the collision coordinator
  15023. this.collisionCoordinator.onMeshAdded(newMesh);
  15024. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15025. };
  15026. Scene.prototype.removeMesh = function (toRemove) {
  15027. var index = this.meshes.indexOf(toRemove);
  15028. if (index !== -1) {
  15029. // Remove from the scene if mesh found
  15030. this.meshes.splice(index, 1);
  15031. }
  15032. //notify the collision coordinator
  15033. this.collisionCoordinator.onMeshRemoved(toRemove);
  15034. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15035. return index;
  15036. };
  15037. Scene.prototype.removeSkeleton = function (toRemove) {
  15038. var index = this.skeletons.indexOf(toRemove);
  15039. if (index !== -1) {
  15040. // Remove from the scene if mesh found
  15041. this.skeletons.splice(index, 1);
  15042. }
  15043. return index;
  15044. };
  15045. Scene.prototype.removeLight = function (toRemove) {
  15046. var index = this.lights.indexOf(toRemove);
  15047. if (index !== -1) {
  15048. // Remove from the scene if mesh found
  15049. this.lights.splice(index, 1);
  15050. }
  15051. this.onLightRemovedObservable.notifyObservers(toRemove);
  15052. return index;
  15053. };
  15054. Scene.prototype.removeCamera = function (toRemove) {
  15055. var index = this.cameras.indexOf(toRemove);
  15056. if (index !== -1) {
  15057. // Remove from the scene if mesh found
  15058. this.cameras.splice(index, 1);
  15059. }
  15060. // Remove from activeCameras
  15061. var index2 = this.activeCameras.indexOf(toRemove);
  15062. if (index2 !== -1) {
  15063. // Remove from the scene if mesh found
  15064. this.activeCameras.splice(index2, 1);
  15065. }
  15066. // Reset the activeCamera
  15067. if (this.activeCamera === toRemove) {
  15068. if (this.cameras.length > 0) {
  15069. this.activeCamera = this.cameras[0];
  15070. }
  15071. else {
  15072. this.activeCamera = null;
  15073. }
  15074. }
  15075. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15076. return index;
  15077. };
  15078. Scene.prototype.addLight = function (newLight) {
  15079. newLight.uniqueId = this._uniqueIdCounter++;
  15080. var position = this.lights.push(newLight);
  15081. this.onNewLightAddedObservable.notifyObservers(newLight);
  15082. };
  15083. Scene.prototype.addCamera = function (newCamera) {
  15084. newCamera.uniqueId = this._uniqueIdCounter++;
  15085. var position = this.cameras.push(newCamera);
  15086. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15087. };
  15088. /**
  15089. * Switch active camera
  15090. * @param {Camera} newCamera - new active camera
  15091. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15092. */
  15093. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15094. if (attachControl === void 0) { attachControl = true; }
  15095. var canvas = this._engine.getRenderingCanvas();
  15096. this.activeCamera.detachControl(canvas);
  15097. this.activeCamera = newCamera;
  15098. if (attachControl) {
  15099. newCamera.attachControl(canvas);
  15100. }
  15101. };
  15102. /**
  15103. * sets the active camera of the scene using its ID
  15104. * @param {string} id - the camera's ID
  15105. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15106. * @see activeCamera
  15107. */
  15108. Scene.prototype.setActiveCameraByID = function (id) {
  15109. var camera = this.getCameraByID(id);
  15110. if (camera) {
  15111. this.activeCamera = camera;
  15112. return camera;
  15113. }
  15114. return null;
  15115. };
  15116. /**
  15117. * sets the active camera of the scene using its name
  15118. * @param {string} name - the camera's name
  15119. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15120. * @see activeCamera
  15121. */
  15122. Scene.prototype.setActiveCameraByName = function (name) {
  15123. var camera = this.getCameraByName(name);
  15124. if (camera) {
  15125. this.activeCamera = camera;
  15126. return camera;
  15127. }
  15128. return null;
  15129. };
  15130. /**
  15131. * get a material using its id
  15132. * @param {string} the material's ID
  15133. * @return {BABYLON.Material|null} the material or null if none found.
  15134. */
  15135. Scene.prototype.getMaterialByID = function (id) {
  15136. for (var index = 0; index < this.materials.length; index++) {
  15137. if (this.materials[index].id === id) {
  15138. return this.materials[index];
  15139. }
  15140. }
  15141. return null;
  15142. };
  15143. /**
  15144. * get a material using its name
  15145. * @param {string} the material's name
  15146. * @return {BABYLON.Material|null} the material or null if none found.
  15147. */
  15148. Scene.prototype.getMaterialByName = function (name) {
  15149. for (var index = 0; index < this.materials.length; index++) {
  15150. if (this.materials[index].name === name) {
  15151. return this.materials[index];
  15152. }
  15153. }
  15154. return null;
  15155. };
  15156. Scene.prototype.getLensFlareSystemByName = function (name) {
  15157. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15158. if (this.lensFlareSystems[index].name === name) {
  15159. return this.lensFlareSystems[index];
  15160. }
  15161. }
  15162. return null;
  15163. };
  15164. Scene.prototype.getLensFlareSystemByID = function (id) {
  15165. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15166. if (this.lensFlareSystems[index].id === id) {
  15167. return this.lensFlareSystems[index];
  15168. }
  15169. }
  15170. return null;
  15171. };
  15172. Scene.prototype.getCameraByID = function (id) {
  15173. for (var index = 0; index < this.cameras.length; index++) {
  15174. if (this.cameras[index].id === id) {
  15175. return this.cameras[index];
  15176. }
  15177. }
  15178. return null;
  15179. };
  15180. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15181. for (var index = 0; index < this.cameras.length; index++) {
  15182. if (this.cameras[index].uniqueId === uniqueId) {
  15183. return this.cameras[index];
  15184. }
  15185. }
  15186. return null;
  15187. };
  15188. /**
  15189. * get a camera using its name
  15190. * @param {string} the camera's name
  15191. * @return {BABYLON.Camera|null} the camera or null if none found.
  15192. */
  15193. Scene.prototype.getCameraByName = function (name) {
  15194. for (var index = 0; index < this.cameras.length; index++) {
  15195. if (this.cameras[index].name === name) {
  15196. return this.cameras[index];
  15197. }
  15198. }
  15199. return null;
  15200. };
  15201. /**
  15202. * get a bone using its id
  15203. * @param {string} the bone's id
  15204. * @return {BABYLON.Bone|null} the bone or null if not found
  15205. */
  15206. Scene.prototype.getBoneByID = function (id) {
  15207. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15208. var skeleton = this.skeletons[skeletonIndex];
  15209. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15210. if (skeleton.bones[boneIndex].id === id) {
  15211. return skeleton.bones[boneIndex];
  15212. }
  15213. }
  15214. }
  15215. return null;
  15216. };
  15217. /**
  15218. * get a bone using its id
  15219. * @param {string} the bone's name
  15220. * @return {BABYLON.Bone|null} the bone or null if not found
  15221. */
  15222. Scene.prototype.getBoneByName = function (name) {
  15223. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15224. var skeleton = this.skeletons[skeletonIndex];
  15225. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15226. if (skeleton.bones[boneIndex].name === name) {
  15227. return skeleton.bones[boneIndex];
  15228. }
  15229. }
  15230. }
  15231. return null;
  15232. };
  15233. /**
  15234. * get a light node using its name
  15235. * @param {string} the light's name
  15236. * @return {BABYLON.Light|null} the light or null if none found.
  15237. */
  15238. Scene.prototype.getLightByName = function (name) {
  15239. for (var index = 0; index < this.lights.length; index++) {
  15240. if (this.lights[index].name === name) {
  15241. return this.lights[index];
  15242. }
  15243. }
  15244. return null;
  15245. };
  15246. /**
  15247. * get a light node using its ID
  15248. * @param {string} the light's id
  15249. * @return {BABYLON.Light|null} the light or null if none found.
  15250. */
  15251. Scene.prototype.getLightByID = function (id) {
  15252. for (var index = 0; index < this.lights.length; index++) {
  15253. if (this.lights[index].id === id) {
  15254. return this.lights[index];
  15255. }
  15256. }
  15257. return null;
  15258. };
  15259. /**
  15260. * get a light node using its scene-generated unique ID
  15261. * @param {number} the light's unique id
  15262. * @return {BABYLON.Light|null} the light or null if none found.
  15263. */
  15264. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15265. for (var index = 0; index < this.lights.length; index++) {
  15266. if (this.lights[index].uniqueId === uniqueId) {
  15267. return this.lights[index];
  15268. }
  15269. }
  15270. return null;
  15271. };
  15272. /**
  15273. * get a particle system by id
  15274. * @param id {number} the particle system id
  15275. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15276. */
  15277. Scene.prototype.getParticleSystemByID = function (id) {
  15278. for (var index = 0; index < this.particleSystems.length; index++) {
  15279. if (this.particleSystems[index].id === id) {
  15280. return this.particleSystems[index];
  15281. }
  15282. }
  15283. return null;
  15284. };
  15285. /**
  15286. * get a geometry using its ID
  15287. * @param {string} the geometry's id
  15288. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15289. */
  15290. Scene.prototype.getGeometryByID = function (id) {
  15291. for (var index = 0; index < this._geometries.length; index++) {
  15292. if (this._geometries[index].id === id) {
  15293. return this._geometries[index];
  15294. }
  15295. }
  15296. return null;
  15297. };
  15298. /**
  15299. * add a new geometry to this scene.
  15300. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15301. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15302. * @return {boolean} was the geometry added or not
  15303. */
  15304. Scene.prototype.pushGeometry = function (geometry, force) {
  15305. if (!force && this.getGeometryByID(geometry.id)) {
  15306. return false;
  15307. }
  15308. this._geometries.push(geometry);
  15309. //notify the collision coordinator
  15310. this.collisionCoordinator.onGeometryAdded(geometry);
  15311. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15312. return true;
  15313. };
  15314. /**
  15315. * Removes an existing geometry
  15316. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15317. * @return {boolean} was the geometry removed or not
  15318. */
  15319. Scene.prototype.removeGeometry = function (geometry) {
  15320. var index = this._geometries.indexOf(geometry);
  15321. if (index > -1) {
  15322. this._geometries.splice(index, 1);
  15323. //notify the collision coordinator
  15324. this.collisionCoordinator.onGeometryDeleted(geometry);
  15325. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15326. return true;
  15327. }
  15328. return false;
  15329. };
  15330. Scene.prototype.getGeometries = function () {
  15331. return this._geometries;
  15332. };
  15333. /**
  15334. * Get the first added mesh found of a given ID
  15335. * @param {string} id - the id to search for
  15336. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15337. */
  15338. Scene.prototype.getMeshByID = function (id) {
  15339. for (var index = 0; index < this.meshes.length; index++) {
  15340. if (this.meshes[index].id === id) {
  15341. return this.meshes[index];
  15342. }
  15343. }
  15344. return null;
  15345. };
  15346. Scene.prototype.getMeshesByID = function (id) {
  15347. return this.meshes.filter(function (m) {
  15348. return m.id === id;
  15349. });
  15350. };
  15351. /**
  15352. * Get a mesh with its auto-generated unique id
  15353. * @param {number} uniqueId - the unique id to search for
  15354. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15355. */
  15356. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15357. for (var index = 0; index < this.meshes.length; index++) {
  15358. if (this.meshes[index].uniqueId === uniqueId) {
  15359. return this.meshes[index];
  15360. }
  15361. }
  15362. return null;
  15363. };
  15364. /**
  15365. * Get a the last added mesh found of a given ID
  15366. * @param {string} id - the id to search for
  15367. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15368. */
  15369. Scene.prototype.getLastMeshByID = function (id) {
  15370. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15371. if (this.meshes[index].id === id) {
  15372. return this.meshes[index];
  15373. }
  15374. }
  15375. return null;
  15376. };
  15377. /**
  15378. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15379. * @param {string} id - the id to search for
  15380. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15381. */
  15382. Scene.prototype.getLastEntryByID = function (id) {
  15383. var index;
  15384. for (index = this.meshes.length - 1; index >= 0; index--) {
  15385. if (this.meshes[index].id === id) {
  15386. return this.meshes[index];
  15387. }
  15388. }
  15389. for (index = this.cameras.length - 1; index >= 0; index--) {
  15390. if (this.cameras[index].id === id) {
  15391. return this.cameras[index];
  15392. }
  15393. }
  15394. for (index = this.lights.length - 1; index >= 0; index--) {
  15395. if (this.lights[index].id === id) {
  15396. return this.lights[index];
  15397. }
  15398. }
  15399. return null;
  15400. };
  15401. Scene.prototype.getNodeByID = function (id) {
  15402. var mesh = this.getMeshByID(id);
  15403. if (mesh) {
  15404. return mesh;
  15405. }
  15406. var light = this.getLightByID(id);
  15407. if (light) {
  15408. return light;
  15409. }
  15410. var camera = this.getCameraByID(id);
  15411. if (camera) {
  15412. return camera;
  15413. }
  15414. var bone = this.getBoneByID(id);
  15415. return bone;
  15416. };
  15417. Scene.prototype.getNodeByName = function (name) {
  15418. var mesh = this.getMeshByName(name);
  15419. if (mesh) {
  15420. return mesh;
  15421. }
  15422. var light = this.getLightByName(name);
  15423. if (light) {
  15424. return light;
  15425. }
  15426. var camera = this.getCameraByName(name);
  15427. if (camera) {
  15428. return camera;
  15429. }
  15430. var bone = this.getBoneByName(name);
  15431. return bone;
  15432. };
  15433. Scene.prototype.getMeshByName = function (name) {
  15434. for (var index = 0; index < this.meshes.length; index++) {
  15435. if (this.meshes[index].name === name) {
  15436. return this.meshes[index];
  15437. }
  15438. }
  15439. return null;
  15440. };
  15441. Scene.prototype.getSoundByName = function (name) {
  15442. var index;
  15443. if (BABYLON.AudioEngine) {
  15444. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15445. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15446. return this.mainSoundTrack.soundCollection[index];
  15447. }
  15448. }
  15449. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15450. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15451. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15452. return this.soundTracks[sdIndex].soundCollection[index];
  15453. }
  15454. }
  15455. }
  15456. }
  15457. return null;
  15458. };
  15459. Scene.prototype.getLastSkeletonByID = function (id) {
  15460. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15461. if (this.skeletons[index].id === id) {
  15462. return this.skeletons[index];
  15463. }
  15464. }
  15465. return null;
  15466. };
  15467. Scene.prototype.getSkeletonById = function (id) {
  15468. for (var index = 0; index < this.skeletons.length; index++) {
  15469. if (this.skeletons[index].id === id) {
  15470. return this.skeletons[index];
  15471. }
  15472. }
  15473. return null;
  15474. };
  15475. Scene.prototype.getSkeletonByName = function (name) {
  15476. for (var index = 0; index < this.skeletons.length; index++) {
  15477. if (this.skeletons[index].name === name) {
  15478. return this.skeletons[index];
  15479. }
  15480. }
  15481. return null;
  15482. };
  15483. Scene.prototype.isActiveMesh = function (mesh) {
  15484. return (this._activeMeshes.indexOf(mesh) !== -1);
  15485. };
  15486. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15487. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15488. var material = subMesh.getMaterial();
  15489. if (mesh.showSubMeshesBoundingBox) {
  15490. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15491. }
  15492. if (material) {
  15493. // Render targets
  15494. if (material.getRenderTargetTextures) {
  15495. if (this._processedMaterials.indexOf(material) === -1) {
  15496. this._processedMaterials.push(material);
  15497. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15498. }
  15499. }
  15500. // Dispatch
  15501. this._activeIndices += subMesh.indexCount;
  15502. this._renderingManager.dispatch(subMesh);
  15503. }
  15504. }
  15505. };
  15506. Scene.prototype._isInIntermediateRendering = function () {
  15507. return this._intermediateRendering;
  15508. };
  15509. Scene.prototype._evaluateActiveMeshes = function () {
  15510. this.activeCamera._activeMeshes.reset();
  15511. this._activeMeshes.reset();
  15512. this._renderingManager.reset();
  15513. this._processedMaterials.reset();
  15514. this._activeParticleSystems.reset();
  15515. this._activeSkeletons.reset();
  15516. this._softwareSkinnedMeshes.reset();
  15517. this._boundingBoxRenderer.reset();
  15518. this._edgesRenderers.reset();
  15519. if (!this._frustumPlanes) {
  15520. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15521. }
  15522. else {
  15523. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15524. }
  15525. // Meshes
  15526. var meshes;
  15527. var len;
  15528. if (this._selectionOctree) {
  15529. var selection = this._selectionOctree.select(this._frustumPlanes);
  15530. meshes = selection.data;
  15531. len = selection.length;
  15532. }
  15533. else {
  15534. len = this.meshes.length;
  15535. meshes = this.meshes;
  15536. }
  15537. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15538. var mesh = meshes[meshIndex];
  15539. if (mesh.isBlocked) {
  15540. continue;
  15541. }
  15542. this._totalVertices += mesh.getTotalVertices();
  15543. if (!mesh.isReady() || !mesh.isEnabled()) {
  15544. continue;
  15545. }
  15546. mesh.computeWorldMatrix();
  15547. // Intersections
  15548. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15549. this._meshesForIntersections.pushNoDuplicate(mesh);
  15550. }
  15551. // Switch to current LOD
  15552. var meshLOD = mesh.getLOD(this.activeCamera);
  15553. if (!meshLOD) {
  15554. continue;
  15555. }
  15556. mesh._preActivate();
  15557. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15558. this._activeMeshes.push(mesh);
  15559. this.activeCamera._activeMeshes.push(mesh);
  15560. mesh._activate(this._renderId);
  15561. this._activeMesh(meshLOD);
  15562. }
  15563. }
  15564. // Particle systems
  15565. var beforeParticlesDate = BABYLON.Tools.Now;
  15566. if (this.particlesEnabled) {
  15567. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15568. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15569. var particleSystem = this.particleSystems[particleIndex];
  15570. if (!particleSystem.isStarted()) {
  15571. continue;
  15572. }
  15573. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15574. this._activeParticleSystems.push(particleSystem);
  15575. particleSystem.animate();
  15576. }
  15577. }
  15578. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15579. }
  15580. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15581. };
  15582. Scene.prototype._activeMesh = function (mesh) {
  15583. if (mesh.skeleton && this.skeletonsEnabled) {
  15584. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15585. if (!mesh.computeBonesUsingShaders) {
  15586. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15587. }
  15588. }
  15589. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15590. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15591. }
  15592. if (mesh._edgesRenderer) {
  15593. this._edgesRenderers.push(mesh._edgesRenderer);
  15594. }
  15595. if (mesh && mesh.subMeshes) {
  15596. // Submeshes Octrees
  15597. var len;
  15598. var subMeshes;
  15599. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15600. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15601. len = intersections.length;
  15602. subMeshes = intersections.data;
  15603. }
  15604. else {
  15605. subMeshes = mesh.subMeshes;
  15606. len = subMeshes.length;
  15607. }
  15608. for (var subIndex = 0; subIndex < len; subIndex++) {
  15609. var subMesh = subMeshes[subIndex];
  15610. this._evaluateSubMesh(subMesh, mesh);
  15611. }
  15612. }
  15613. };
  15614. Scene.prototype.updateTransformMatrix = function (force) {
  15615. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15616. };
  15617. Scene.prototype._renderForCamera = function (camera) {
  15618. var engine = this._engine;
  15619. this.activeCamera = camera;
  15620. if (!this.activeCamera)
  15621. throw new Error("Active camera not set");
  15622. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15623. // Viewport
  15624. engine.setViewport(this.activeCamera.viewport);
  15625. // Camera
  15626. this.resetCachedMaterial();
  15627. this._renderId++;
  15628. this.updateTransformMatrix();
  15629. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15630. // Meshes
  15631. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15632. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15633. this._evaluateActiveMeshes();
  15634. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15635. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15636. // Skeletons
  15637. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15638. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15639. skeleton.prepare();
  15640. }
  15641. // Software skinning
  15642. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15643. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15644. mesh.applySkeleton(mesh.skeleton);
  15645. }
  15646. // Render targets
  15647. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15648. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15649. this._intermediateRendering = true;
  15650. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15651. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15652. var renderTarget = this._renderTargets.data[renderIndex];
  15653. if (renderTarget._shouldRender()) {
  15654. this._renderId++;
  15655. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15656. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15657. }
  15658. }
  15659. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15660. this._intermediateRendering = false;
  15661. this._renderId++;
  15662. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15663. }
  15664. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15665. // Prepare Frame
  15666. this.postProcessManager._prepareFrame();
  15667. var beforeRenderDate = BABYLON.Tools.Now;
  15668. // Backgrounds
  15669. var layerIndex;
  15670. var layer;
  15671. if (this.layers.length) {
  15672. engine.setDepthBuffer(false);
  15673. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15674. layer = this.layers[layerIndex];
  15675. if (layer.isBackground) {
  15676. layer.render();
  15677. }
  15678. }
  15679. engine.setDepthBuffer(true);
  15680. }
  15681. // Render
  15682. BABYLON.Tools.StartPerformanceCounter("Main render");
  15683. this._renderingManager.render(null, null, true, true);
  15684. BABYLON.Tools.EndPerformanceCounter("Main render");
  15685. // Bounding boxes
  15686. this._boundingBoxRenderer.render();
  15687. // Edges
  15688. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15689. this._edgesRenderers.data[edgesRendererIndex].render();
  15690. }
  15691. // Lens flares
  15692. if (this.lensFlaresEnabled) {
  15693. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15694. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15695. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15696. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15697. lensFlareSystem.render();
  15698. }
  15699. }
  15700. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15701. }
  15702. // Foregrounds
  15703. if (this.layers.length) {
  15704. engine.setDepthBuffer(false);
  15705. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15706. layer = this.layers[layerIndex];
  15707. if (!layer.isBackground) {
  15708. layer.render();
  15709. }
  15710. }
  15711. engine.setDepthBuffer(true);
  15712. }
  15713. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15714. // Finalize frame
  15715. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15716. // Update camera
  15717. this.activeCamera._updateFromScene();
  15718. // Reset some special arrays
  15719. this._renderTargets.reset();
  15720. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15721. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15722. };
  15723. Scene.prototype._processSubCameras = function (camera) {
  15724. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15725. this._renderForCamera(camera);
  15726. return;
  15727. }
  15728. // rig cameras
  15729. for (var index = 0; index < camera._rigCameras.length; index++) {
  15730. this._renderForCamera(camera._rigCameras[index]);
  15731. }
  15732. this.activeCamera = camera;
  15733. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15734. // Update camera
  15735. this.activeCamera._updateFromScene();
  15736. };
  15737. Scene.prototype._checkIntersections = function () {
  15738. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15739. var sourceMesh = this._meshesForIntersections.data[index];
  15740. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15741. var action = sourceMesh.actionManager.actions[actionIndex];
  15742. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15743. var parameters = action.getTriggerParameter();
  15744. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15745. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15746. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15747. if (areIntersecting && currentIntersectionInProgress === -1) {
  15748. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15749. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15750. sourceMesh._intersectionsInProgress.push(otherMesh);
  15751. }
  15752. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15753. sourceMesh._intersectionsInProgress.push(otherMesh);
  15754. }
  15755. }
  15756. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15757. //They intersected, and now they don't.
  15758. //is this trigger an exit trigger? execute an event.
  15759. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15760. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15761. }
  15762. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15763. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15764. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15765. }
  15766. }
  15767. }
  15768. }
  15769. }
  15770. };
  15771. Scene.prototype.render = function () {
  15772. var startDate = BABYLON.Tools.Now;
  15773. this._particlesDuration = 0;
  15774. this._spritesDuration = 0;
  15775. this._activeParticles = 0;
  15776. this._renderDuration = 0;
  15777. this._renderTargetsDuration = 0;
  15778. this._evaluateActiveMeshesDuration = 0;
  15779. this._totalVertices = 0;
  15780. this._activeIndices = 0;
  15781. this._activeBones = 0;
  15782. this.getEngine().resetDrawCalls();
  15783. this._meshesForIntersections.reset();
  15784. this.resetCachedMaterial();
  15785. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15786. // Actions
  15787. if (this.actionManager) {
  15788. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15789. }
  15790. //Simplification Queue
  15791. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15792. this.simplificationQueue.executeNext();
  15793. }
  15794. // Animations
  15795. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15796. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15797. this._animate();
  15798. // Physics
  15799. if (this._physicsEngine) {
  15800. BABYLON.Tools.StartPerformanceCounter("Physics");
  15801. this._physicsEngine._step(deltaTime / 1000.0);
  15802. BABYLON.Tools.EndPerformanceCounter("Physics");
  15803. }
  15804. // Before render
  15805. this.onBeforeRenderObservable.notifyObservers(this);
  15806. // Customs render targets
  15807. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15808. var engine = this.getEngine();
  15809. var currentActiveCamera = this.activeCamera;
  15810. if (this.renderTargetsEnabled) {
  15811. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15812. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15813. var renderTarget = this.customRenderTargets[customIndex];
  15814. if (renderTarget._shouldRender()) {
  15815. this._renderId++;
  15816. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15817. if (!this.activeCamera)
  15818. throw new Error("Active camera not set");
  15819. // Viewport
  15820. engine.setViewport(this.activeCamera.viewport);
  15821. // Camera
  15822. this.updateTransformMatrix();
  15823. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15824. }
  15825. }
  15826. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15827. this._renderId++;
  15828. }
  15829. if (this.customRenderTargets.length > 0) {
  15830. engine.restoreDefaultFramebuffer();
  15831. }
  15832. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15833. this.activeCamera = currentActiveCamera;
  15834. // Procedural textures
  15835. if (this.proceduralTexturesEnabled) {
  15836. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15837. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15838. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15839. if (proceduralTexture._shouldRender()) {
  15840. proceduralTexture.render();
  15841. }
  15842. }
  15843. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15844. }
  15845. // Clear
  15846. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15847. // Shadows
  15848. if (this.shadowsEnabled) {
  15849. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15850. var light = this.lights[lightIndex];
  15851. var shadowGenerator = light.getShadowGenerator();
  15852. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15853. this._renderTargets.push(shadowGenerator.getShadowMap());
  15854. }
  15855. }
  15856. }
  15857. // Depth renderer
  15858. if (this._depthRenderer) {
  15859. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15860. }
  15861. // RenderPipeline
  15862. this.postProcessRenderPipelineManager.update();
  15863. // Multi-cameras?
  15864. if (this.activeCameras.length > 0) {
  15865. var currentRenderId = this._renderId;
  15866. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15867. this._renderId = currentRenderId;
  15868. if (cameraIndex > 0) {
  15869. this._engine.clear(0, false, true);
  15870. }
  15871. this._processSubCameras(this.activeCameras[cameraIndex]);
  15872. }
  15873. }
  15874. else {
  15875. if (!this.activeCamera) {
  15876. throw new Error("No camera defined");
  15877. }
  15878. this._processSubCameras(this.activeCamera);
  15879. }
  15880. // Intersection checks
  15881. this._checkIntersections();
  15882. // Update the audio listener attached to the camera
  15883. if (BABYLON.AudioEngine) {
  15884. this._updateAudioParameters();
  15885. }
  15886. // After render
  15887. if (this.afterRender) {
  15888. this.afterRender();
  15889. }
  15890. this.onAfterRenderObservable.notifyObservers(this);
  15891. // Cleaning
  15892. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15893. this._toBeDisposed.data[index].dispose();
  15894. this._toBeDisposed[index] = null;
  15895. }
  15896. this._toBeDisposed.reset();
  15897. if (this.dumpNextRenderTargets) {
  15898. this.dumpNextRenderTargets = false;
  15899. }
  15900. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15901. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15902. };
  15903. Scene.prototype._updateAudioParameters = function () {
  15904. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15905. return;
  15906. }
  15907. var listeningCamera;
  15908. var audioEngine = BABYLON.Engine.audioEngine;
  15909. if (this.activeCameras.length > 0) {
  15910. listeningCamera = this.activeCameras[0];
  15911. }
  15912. else {
  15913. listeningCamera = this.activeCamera;
  15914. }
  15915. if (listeningCamera && audioEngine.canUseWebAudio) {
  15916. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15917. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15918. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15919. cameraDirection.normalize();
  15920. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15921. var i;
  15922. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15923. var sound = this.mainSoundTrack.soundCollection[i];
  15924. if (sound.useCustomAttenuation) {
  15925. sound.updateDistanceFromListener();
  15926. }
  15927. }
  15928. for (i = 0; i < this.soundTracks.length; i++) {
  15929. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15930. sound = this.soundTracks[i].soundCollection[j];
  15931. if (sound.useCustomAttenuation) {
  15932. sound.updateDistanceFromListener();
  15933. }
  15934. }
  15935. }
  15936. }
  15937. };
  15938. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15939. // Audio
  15940. get: function () {
  15941. return this._audioEnabled;
  15942. },
  15943. set: function (value) {
  15944. this._audioEnabled = value;
  15945. if (BABYLON.AudioEngine) {
  15946. if (this._audioEnabled) {
  15947. this._enableAudio();
  15948. }
  15949. else {
  15950. this._disableAudio();
  15951. }
  15952. }
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Scene.prototype._disableAudio = function () {
  15958. var i;
  15959. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15960. this.mainSoundTrack.soundCollection[i].pause();
  15961. }
  15962. for (i = 0; i < this.soundTracks.length; i++) {
  15963. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15964. this.soundTracks[i].soundCollection[j].pause();
  15965. }
  15966. }
  15967. };
  15968. Scene.prototype._enableAudio = function () {
  15969. var i;
  15970. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15971. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15972. this.mainSoundTrack.soundCollection[i].play();
  15973. }
  15974. }
  15975. for (i = 0; i < this.soundTracks.length; i++) {
  15976. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15977. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15978. this.soundTracks[i].soundCollection[j].play();
  15979. }
  15980. }
  15981. }
  15982. };
  15983. Object.defineProperty(Scene.prototype, "headphone", {
  15984. get: function () {
  15985. return this._headphone;
  15986. },
  15987. set: function (value) {
  15988. this._headphone = value;
  15989. if (BABYLON.AudioEngine) {
  15990. if (this._headphone) {
  15991. this._switchAudioModeForHeadphones();
  15992. }
  15993. else {
  15994. this._switchAudioModeForNormalSpeakers();
  15995. }
  15996. }
  15997. },
  15998. enumerable: true,
  15999. configurable: true
  16000. });
  16001. Scene.prototype._switchAudioModeForHeadphones = function () {
  16002. this.mainSoundTrack.switchPanningModelToHRTF();
  16003. for (var i = 0; i < this.soundTracks.length; i++) {
  16004. this.soundTracks[i].switchPanningModelToHRTF();
  16005. }
  16006. };
  16007. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16008. this.mainSoundTrack.switchPanningModelToEqualPower();
  16009. for (var i = 0; i < this.soundTracks.length; i++) {
  16010. this.soundTracks[i].switchPanningModelToEqualPower();
  16011. }
  16012. };
  16013. Scene.prototype.enableDepthRenderer = function () {
  16014. if (this._depthRenderer) {
  16015. return this._depthRenderer;
  16016. }
  16017. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16018. return this._depthRenderer;
  16019. };
  16020. Scene.prototype.disableDepthRenderer = function () {
  16021. if (!this._depthRenderer) {
  16022. return;
  16023. }
  16024. this._depthRenderer.dispose();
  16025. this._depthRenderer = null;
  16026. };
  16027. Scene.prototype.freezeMaterials = function () {
  16028. for (var i = 0; i < this.materials.length; i++) {
  16029. this.materials[i].freeze();
  16030. }
  16031. };
  16032. Scene.prototype.unfreezeMaterials = function () {
  16033. for (var i = 0; i < this.materials.length; i++) {
  16034. this.materials[i].unfreeze();
  16035. }
  16036. };
  16037. Scene.prototype.dispose = function () {
  16038. this.beforeRender = null;
  16039. this.afterRender = null;
  16040. this.skeletons = [];
  16041. this._boundingBoxRenderer.dispose();
  16042. if (this._depthRenderer) {
  16043. this._depthRenderer.dispose();
  16044. }
  16045. // Debug layer
  16046. this.debugLayer.hide();
  16047. // Events
  16048. if (this.onDispose) {
  16049. this.onDispose();
  16050. }
  16051. this.onBeforeRenderObservable.clear();
  16052. this.onAfterRenderObservable.clear();
  16053. this.detachControl();
  16054. // Release sounds & sounds tracks
  16055. if (BABYLON.AudioEngine) {
  16056. this.disposeSounds();
  16057. }
  16058. // Detach cameras
  16059. var canvas = this._engine.getRenderingCanvas();
  16060. var index;
  16061. for (index = 0; index < this.cameras.length; index++) {
  16062. this.cameras[index].detachControl(canvas);
  16063. }
  16064. // Release lights
  16065. while (this.lights.length) {
  16066. this.lights[0].dispose();
  16067. }
  16068. // Release meshes
  16069. while (this.meshes.length) {
  16070. this.meshes[0].dispose(true);
  16071. }
  16072. // Release cameras
  16073. while (this.cameras.length) {
  16074. this.cameras[0].dispose();
  16075. }
  16076. // Release materials
  16077. while (this.materials.length) {
  16078. this.materials[0].dispose();
  16079. }
  16080. // Release particles
  16081. while (this.particleSystems.length) {
  16082. this.particleSystems[0].dispose();
  16083. }
  16084. // Release sprites
  16085. while (this.spriteManagers.length) {
  16086. this.spriteManagers[0].dispose();
  16087. }
  16088. // Release layers
  16089. while (this.layers.length) {
  16090. this.layers[0].dispose();
  16091. }
  16092. // Release textures
  16093. while (this.textures.length) {
  16094. this.textures[0].dispose();
  16095. }
  16096. // Post-processes
  16097. this.postProcessManager.dispose();
  16098. // Physics
  16099. if (this._physicsEngine) {
  16100. this.disablePhysicsEngine();
  16101. }
  16102. // Remove from engine
  16103. index = this._engine.scenes.indexOf(this);
  16104. if (index > -1) {
  16105. this._engine.scenes.splice(index, 1);
  16106. }
  16107. this._engine.wipeCaches();
  16108. };
  16109. // Release sounds & sounds tracks
  16110. Scene.prototype.disposeSounds = function () {
  16111. this.mainSoundTrack.dispose();
  16112. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16113. this.soundTracks[scIndex].dispose();
  16114. }
  16115. };
  16116. // Octrees
  16117. Scene.prototype.getWorldExtends = function () {
  16118. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16119. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16120. for (var index = 0; index < this.meshes.length; index++) {
  16121. var mesh = this.meshes[index];
  16122. mesh.computeWorldMatrix(true);
  16123. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16124. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16125. BABYLON.Tools.CheckExtends(minBox, min, max);
  16126. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16127. }
  16128. return {
  16129. min: min,
  16130. max: max
  16131. };
  16132. };
  16133. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16134. if (maxCapacity === void 0) { maxCapacity = 64; }
  16135. if (maxDepth === void 0) { maxDepth = 2; }
  16136. if (!this._selectionOctree) {
  16137. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16138. }
  16139. var worldExtends = this.getWorldExtends();
  16140. // Update octree
  16141. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16142. return this._selectionOctree;
  16143. };
  16144. // Picking
  16145. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16146. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16147. var engine = this._engine;
  16148. if (!camera) {
  16149. if (!this.activeCamera)
  16150. throw new Error("Active camera not set");
  16151. camera = this.activeCamera;
  16152. }
  16153. var cameraViewport = camera.viewport;
  16154. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16155. // Moving coordinates to local viewport world
  16156. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16157. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16158. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16159. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16160. };
  16161. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16162. var engine = this._engine;
  16163. if (!camera) {
  16164. if (!this.activeCamera)
  16165. throw new Error("Active camera not set");
  16166. camera = this.activeCamera;
  16167. }
  16168. var cameraViewport = camera.viewport;
  16169. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16170. var identity = BABYLON.Matrix.Identity();
  16171. // Moving coordinates to local viewport world
  16172. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16173. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16174. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16175. };
  16176. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16177. var pickingInfo = null;
  16178. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16179. var mesh = this.meshes[meshIndex];
  16180. if (predicate) {
  16181. if (!predicate(mesh)) {
  16182. continue;
  16183. }
  16184. }
  16185. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16186. continue;
  16187. }
  16188. var world = mesh.getWorldMatrix();
  16189. var ray = rayFunction(world);
  16190. var result = mesh.intersects(ray, fastCheck);
  16191. if (!result || !result.hit)
  16192. continue;
  16193. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16194. continue;
  16195. pickingInfo = result;
  16196. if (fastCheck) {
  16197. break;
  16198. }
  16199. }
  16200. return pickingInfo || new BABYLON.PickingInfo();
  16201. };
  16202. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16203. var pickingInfo = null;
  16204. camera = camera || this.activeCamera;
  16205. if (this.spriteManagers.length > 0) {
  16206. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16207. var spriteManager = this.spriteManagers[spriteIndex];
  16208. if (!spriteManager.isPickable) {
  16209. continue;
  16210. }
  16211. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16212. if (!result || !result.hit)
  16213. continue;
  16214. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16215. continue;
  16216. pickingInfo = result;
  16217. if (fastCheck) {
  16218. break;
  16219. }
  16220. }
  16221. }
  16222. return pickingInfo || new BABYLON.PickingInfo();
  16223. };
  16224. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16225. var _this = this;
  16226. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16227. /// <param name="x">X position on screen</param>
  16228. /// <param name="y">Y position on screen</param>
  16229. /// <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>
  16230. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16231. /// <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>
  16232. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16233. };
  16234. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16235. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16236. /// <param name="x">X position on screen</param>
  16237. /// <param name="y">Y position on screen</param>
  16238. /// <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>
  16239. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16240. /// <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>
  16241. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16242. };
  16243. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16244. var _this = this;
  16245. return this._internalPick(function (world) {
  16246. if (!_this._pickWithRayInverseMatrix) {
  16247. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16248. }
  16249. world.invertToRef(_this._pickWithRayInverseMatrix);
  16250. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16251. }, predicate, fastCheck);
  16252. };
  16253. Scene.prototype.setPointerOverMesh = function (mesh) {
  16254. if (this._pointerOverMesh === mesh) {
  16255. return;
  16256. }
  16257. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16258. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16259. }
  16260. this._pointerOverMesh = mesh;
  16261. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16262. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16263. }
  16264. };
  16265. Scene.prototype.getPointerOverMesh = function () {
  16266. return this._pointerOverMesh;
  16267. };
  16268. Scene.prototype.setPointerOverSprite = function (sprite) {
  16269. if (this._pointerOverSprite === sprite) {
  16270. return;
  16271. }
  16272. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16273. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16274. }
  16275. this._pointerOverSprite = sprite;
  16276. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16277. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16278. }
  16279. };
  16280. Scene.prototype.getPointerOverSprite = function () {
  16281. return this._pointerOverSprite;
  16282. };
  16283. // Physics
  16284. Scene.prototype.getPhysicsEngine = function () {
  16285. return this._physicsEngine;
  16286. };
  16287. /**
  16288. * Enables physics to the current scene
  16289. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16290. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16291. * @return {boolean} was the physics engine initialized
  16292. */
  16293. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16294. if (this._physicsEngine) {
  16295. return true;
  16296. }
  16297. try {
  16298. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16299. return true;
  16300. }
  16301. catch (e) {
  16302. BABYLON.Tools.Error(e.message);
  16303. return false;
  16304. }
  16305. };
  16306. Scene.prototype.disablePhysicsEngine = function () {
  16307. if (!this._physicsEngine) {
  16308. return;
  16309. }
  16310. this._physicsEngine.dispose();
  16311. this._physicsEngine = undefined;
  16312. };
  16313. Scene.prototype.isPhysicsEnabled = function () {
  16314. return this._physicsEngine !== undefined;
  16315. };
  16316. /**
  16317. *
  16318. * Sets the gravity of the physics engine (and NOT of the scene)
  16319. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16320. */
  16321. Scene.prototype.setGravity = function (gravity) {
  16322. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16323. if (!this._physicsEngine) {
  16324. return;
  16325. }
  16326. this._physicsEngine.setGravity(gravity);
  16327. };
  16328. /**
  16329. * Legacy support, using the new API
  16330. * @Deprecated
  16331. */
  16332. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16333. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16334. if (parts.parts) {
  16335. options = parts;
  16336. parts = parts.parts;
  16337. }
  16338. var mainMesh = parts[0].mesh;
  16339. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16340. for (var index = 1; index < parts.length; index++) {
  16341. var mesh = parts[index].mesh;
  16342. if (mesh.parent !== mainMesh) {
  16343. mesh.position = mesh.position.subtract(mainMesh.position);
  16344. mesh.parent = mainMesh;
  16345. }
  16346. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16347. }
  16348. mainMesh.physicsImpostor.forceUpdate();
  16349. };
  16350. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16351. var mesh = compound.parts[0].mesh;
  16352. mesh.physicsImpostor.dispose();
  16353. mesh.physicsImpostor = null;
  16354. };
  16355. // Misc.
  16356. Scene.prototype.createDefaultCameraOrLight = function () {
  16357. // Light
  16358. if (this.lights.length === 0) {
  16359. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16360. }
  16361. // Camera
  16362. if (!this.activeCamera) {
  16363. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16364. // Compute position
  16365. var worldExtends = this.getWorldExtends();
  16366. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16367. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16368. camera.setTarget(worldCenter);
  16369. this.activeCamera = camera;
  16370. }
  16371. };
  16372. // Tags
  16373. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16374. if (tagsQuery === undefined) {
  16375. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16376. return list;
  16377. }
  16378. var listByTags = [];
  16379. forEach = forEach || (function (item) { return; });
  16380. for (var i in list) {
  16381. var item = list[i];
  16382. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16383. listByTags.push(item);
  16384. forEach(item);
  16385. }
  16386. }
  16387. return listByTags;
  16388. };
  16389. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16390. return this._getByTags(this.meshes, tagsQuery, forEach);
  16391. };
  16392. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16393. return this._getByTags(this.cameras, tagsQuery, forEach);
  16394. };
  16395. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16396. return this._getByTags(this.lights, tagsQuery, forEach);
  16397. };
  16398. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16399. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16400. };
  16401. // Statics
  16402. Scene._FOGMODE_NONE = 0;
  16403. Scene._FOGMODE_EXP = 1;
  16404. Scene._FOGMODE_EXP2 = 2;
  16405. Scene._FOGMODE_LINEAR = 3;
  16406. Scene.MinDeltaTime = 1.0;
  16407. Scene.MaxDeltaTime = 1000.0;
  16408. return Scene;
  16409. })();
  16410. BABYLON.Scene = Scene;
  16411. })(BABYLON || (BABYLON = {}));
  16412. var BABYLON;
  16413. (function (BABYLON) {
  16414. var VertexBuffer = (function () {
  16415. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16416. if (engine instanceof BABYLON.Mesh) {
  16417. this._engine = engine.getScene().getEngine();
  16418. }
  16419. else {
  16420. this._engine = engine;
  16421. }
  16422. this._updatable = updatable;
  16423. this._data = data;
  16424. if (!postponeInternalCreation) {
  16425. this.create();
  16426. }
  16427. this._kind = kind;
  16428. if (stride) {
  16429. this._strideSize = stride;
  16430. return;
  16431. }
  16432. // Deduce stride from kind
  16433. switch (kind) {
  16434. case VertexBuffer.PositionKind:
  16435. this._strideSize = 3;
  16436. break;
  16437. case VertexBuffer.NormalKind:
  16438. this._strideSize = 3;
  16439. break;
  16440. case VertexBuffer.UVKind:
  16441. case VertexBuffer.UV2Kind:
  16442. case VertexBuffer.UV3Kind:
  16443. case VertexBuffer.UV4Kind:
  16444. case VertexBuffer.UV5Kind:
  16445. case VertexBuffer.UV6Kind:
  16446. this._strideSize = 2;
  16447. break;
  16448. case VertexBuffer.ColorKind:
  16449. this._strideSize = 4;
  16450. break;
  16451. case VertexBuffer.MatricesIndicesKind:
  16452. case VertexBuffer.MatricesIndicesExtraKind:
  16453. this._strideSize = 4;
  16454. break;
  16455. case VertexBuffer.MatricesWeightsKind:
  16456. case VertexBuffer.MatricesWeightsExtraKind:
  16457. this._strideSize = 4;
  16458. break;
  16459. }
  16460. }
  16461. // Properties
  16462. VertexBuffer.prototype.isUpdatable = function () {
  16463. return this._updatable;
  16464. };
  16465. VertexBuffer.prototype.getData = function () {
  16466. return this._data;
  16467. };
  16468. VertexBuffer.prototype.getBuffer = function () {
  16469. return this._buffer;
  16470. };
  16471. VertexBuffer.prototype.getStrideSize = function () {
  16472. return this._strideSize;
  16473. };
  16474. // Methods
  16475. VertexBuffer.prototype.create = function (data) {
  16476. if (!data && this._buffer) {
  16477. return; // nothing to do
  16478. }
  16479. data = data || this._data;
  16480. if (!this._buffer) {
  16481. if (this._updatable) {
  16482. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16483. }
  16484. else {
  16485. this._buffer = this._engine.createVertexBuffer(data);
  16486. }
  16487. }
  16488. if (this._updatable) {
  16489. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16490. this._data = data;
  16491. }
  16492. };
  16493. VertexBuffer.prototype.update = function (data) {
  16494. this.create(data);
  16495. };
  16496. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16497. if (!this._buffer) {
  16498. return;
  16499. }
  16500. if (this._updatable) {
  16501. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16502. this._data = null;
  16503. }
  16504. };
  16505. VertexBuffer.prototype.dispose = function () {
  16506. if (!this._buffer) {
  16507. return;
  16508. }
  16509. if (this._engine._releaseBuffer(this._buffer)) {
  16510. this._buffer = null;
  16511. }
  16512. };
  16513. Object.defineProperty(VertexBuffer, "PositionKind", {
  16514. get: function () {
  16515. return VertexBuffer._PositionKind;
  16516. },
  16517. enumerable: true,
  16518. configurable: true
  16519. });
  16520. Object.defineProperty(VertexBuffer, "NormalKind", {
  16521. get: function () {
  16522. return VertexBuffer._NormalKind;
  16523. },
  16524. enumerable: true,
  16525. configurable: true
  16526. });
  16527. Object.defineProperty(VertexBuffer, "UVKind", {
  16528. get: function () {
  16529. return VertexBuffer._UVKind;
  16530. },
  16531. enumerable: true,
  16532. configurable: true
  16533. });
  16534. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16535. get: function () {
  16536. return VertexBuffer._UV2Kind;
  16537. },
  16538. enumerable: true,
  16539. configurable: true
  16540. });
  16541. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16542. get: function () {
  16543. return VertexBuffer._UV3Kind;
  16544. },
  16545. enumerable: true,
  16546. configurable: true
  16547. });
  16548. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16549. get: function () {
  16550. return VertexBuffer._UV4Kind;
  16551. },
  16552. enumerable: true,
  16553. configurable: true
  16554. });
  16555. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16556. get: function () {
  16557. return VertexBuffer._UV5Kind;
  16558. },
  16559. enumerable: true,
  16560. configurable: true
  16561. });
  16562. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16563. get: function () {
  16564. return VertexBuffer._UV6Kind;
  16565. },
  16566. enumerable: true,
  16567. configurable: true
  16568. });
  16569. Object.defineProperty(VertexBuffer, "ColorKind", {
  16570. get: function () {
  16571. return VertexBuffer._ColorKind;
  16572. },
  16573. enumerable: true,
  16574. configurable: true
  16575. });
  16576. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16577. get: function () {
  16578. return VertexBuffer._MatricesIndicesKind;
  16579. },
  16580. enumerable: true,
  16581. configurable: true
  16582. });
  16583. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16584. get: function () {
  16585. return VertexBuffer._MatricesWeightsKind;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16591. get: function () {
  16592. return VertexBuffer._MatricesIndicesExtraKind;
  16593. },
  16594. enumerable: true,
  16595. configurable: true
  16596. });
  16597. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16598. get: function () {
  16599. return VertexBuffer._MatricesWeightsExtraKind;
  16600. },
  16601. enumerable: true,
  16602. configurable: true
  16603. });
  16604. // Enums
  16605. VertexBuffer._PositionKind = "position";
  16606. VertexBuffer._NormalKind = "normal";
  16607. VertexBuffer._UVKind = "uv";
  16608. VertexBuffer._UV2Kind = "uv2";
  16609. VertexBuffer._UV3Kind = "uv3";
  16610. VertexBuffer._UV4Kind = "uv4";
  16611. VertexBuffer._UV5Kind = "uv5";
  16612. VertexBuffer._UV6Kind = "uv6";
  16613. VertexBuffer._ColorKind = "color";
  16614. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16615. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16616. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16617. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16618. return VertexBuffer;
  16619. })();
  16620. BABYLON.VertexBuffer = VertexBuffer;
  16621. })(BABYLON || (BABYLON = {}));
  16622. var BABYLON;
  16623. (function (BABYLON) {
  16624. /**
  16625. * Creates an instance based on a source mesh.
  16626. */
  16627. var InstancedMesh = (function (_super) {
  16628. __extends(InstancedMesh, _super);
  16629. function InstancedMesh(name, source) {
  16630. _super.call(this, name, source.getScene());
  16631. source.instances.push(this);
  16632. this._sourceMesh = source;
  16633. this.position.copyFrom(source.position);
  16634. this.rotation.copyFrom(source.rotation);
  16635. this.scaling.copyFrom(source.scaling);
  16636. if (source.rotationQuaternion) {
  16637. this.rotationQuaternion = source.rotationQuaternion.clone();
  16638. }
  16639. this.infiniteDistance = source.infiniteDistance;
  16640. this.setPivotMatrix(source.getPivotMatrix());
  16641. this.refreshBoundingInfo();
  16642. this._syncSubMeshes();
  16643. }
  16644. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16645. // Methods
  16646. get: function () {
  16647. return this._sourceMesh.receiveShadows;
  16648. },
  16649. enumerable: true,
  16650. configurable: true
  16651. });
  16652. Object.defineProperty(InstancedMesh.prototype, "material", {
  16653. get: function () {
  16654. return this._sourceMesh.material;
  16655. },
  16656. enumerable: true,
  16657. configurable: true
  16658. });
  16659. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16660. get: function () {
  16661. return this._sourceMesh.visibility;
  16662. },
  16663. enumerable: true,
  16664. configurable: true
  16665. });
  16666. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16667. get: function () {
  16668. return this._sourceMesh.skeleton;
  16669. },
  16670. enumerable: true,
  16671. configurable: true
  16672. });
  16673. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16674. get: function () {
  16675. return this._sourceMesh.renderingGroupId;
  16676. },
  16677. enumerable: true,
  16678. configurable: true
  16679. });
  16680. InstancedMesh.prototype.getTotalVertices = function () {
  16681. return this._sourceMesh.getTotalVertices();
  16682. };
  16683. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16684. get: function () {
  16685. return this._sourceMesh;
  16686. },
  16687. enumerable: true,
  16688. configurable: true
  16689. });
  16690. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16691. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16692. };
  16693. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16694. return this._sourceMesh.isVerticesDataPresent(kind);
  16695. };
  16696. InstancedMesh.prototype.getIndices = function () {
  16697. return this._sourceMesh.getIndices();
  16698. };
  16699. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16700. get: function () {
  16701. return this._sourceMesh._positions;
  16702. },
  16703. enumerable: true,
  16704. configurable: true
  16705. });
  16706. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16707. var meshBB = this._sourceMesh.getBoundingInfo();
  16708. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16709. this._updateBoundingInfo();
  16710. };
  16711. InstancedMesh.prototype._preActivate = function () {
  16712. if (this._currentLOD) {
  16713. this._currentLOD._preActivate();
  16714. }
  16715. };
  16716. InstancedMesh.prototype._activate = function (renderId) {
  16717. if (this._currentLOD) {
  16718. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16719. }
  16720. };
  16721. InstancedMesh.prototype.getLOD = function (camera) {
  16722. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16723. if (this._currentLOD === this.sourceMesh) {
  16724. return this;
  16725. }
  16726. return this._currentLOD;
  16727. };
  16728. InstancedMesh.prototype._syncSubMeshes = function () {
  16729. this.releaseSubMeshes();
  16730. if (this._sourceMesh.subMeshes) {
  16731. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16732. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16733. }
  16734. }
  16735. };
  16736. InstancedMesh.prototype._generatePointsArray = function () {
  16737. return this._sourceMesh._generatePointsArray();
  16738. };
  16739. // Clone
  16740. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16741. var result = this._sourceMesh.createInstance(name);
  16742. // Deep copy
  16743. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  16744. // Bounding info
  16745. this.refreshBoundingInfo();
  16746. // Parent
  16747. if (newParent) {
  16748. result.parent = newParent;
  16749. }
  16750. if (!doNotCloneChildren) {
  16751. // Children
  16752. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16753. var mesh = this.getScene().meshes[index];
  16754. if (mesh.parent === this) {
  16755. mesh.clone(mesh.name, result);
  16756. }
  16757. }
  16758. }
  16759. result.computeWorldMatrix(true);
  16760. return result;
  16761. };
  16762. // Dispoe
  16763. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16764. // Remove from mesh
  16765. var index = this._sourceMesh.instances.indexOf(this);
  16766. this._sourceMesh.instances.splice(index, 1);
  16767. _super.prototype.dispose.call(this, doNotRecurse);
  16768. };
  16769. return InstancedMesh;
  16770. })(BABYLON.AbstractMesh);
  16771. BABYLON.InstancedMesh = InstancedMesh;
  16772. })(BABYLON || (BABYLON = {}));
  16773. var BABYLON;
  16774. (function (BABYLON) {
  16775. var _InstancesBatch = (function () {
  16776. function _InstancesBatch() {
  16777. this.mustReturn = false;
  16778. this.visibleInstances = new Array();
  16779. this.renderSelf = new Array();
  16780. }
  16781. return _InstancesBatch;
  16782. })();
  16783. BABYLON._InstancesBatch = _InstancesBatch;
  16784. var Mesh = (function (_super) {
  16785. __extends(Mesh, _super);
  16786. /**
  16787. * @constructor
  16788. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16789. * @param {Scene} scene - The scene to add this mesh to.
  16790. * @param {Node} parent - The parent of this mesh, if it has one
  16791. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16792. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16793. * When false, achieved by calling a clone(), also passing False.
  16794. * This will make creation of children, recursive.
  16795. */
  16796. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16797. if (parent === void 0) { parent = null; }
  16798. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16799. _super.call(this, name, scene);
  16800. // Events
  16801. /**
  16802. * An event triggered before rendering the mesh
  16803. * @type {BABYLON.Observable}
  16804. */
  16805. this.onBeforeRenderObservable = new BABYLON.Observable();
  16806. /**
  16807. * An event triggered after rendering the mesh
  16808. * @type {BABYLON.Observable}
  16809. */
  16810. this.onAfterRenderObservable = new BABYLON.Observable();
  16811. /**
  16812. * An event triggered before drawing the mesh
  16813. * @type {BABYLON.Observable}
  16814. */
  16815. this.onBeforeDrawObservable = new BABYLON.Observable();
  16816. // Members
  16817. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16818. this.instances = new Array();
  16819. this._LODLevels = new Array();
  16820. this._visibleInstances = {};
  16821. this._renderIdForInstances = new Array();
  16822. this._batchCache = new _InstancesBatch();
  16823. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16824. this._sideOrientation = Mesh._DEFAULTSIDE;
  16825. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16826. if (source) {
  16827. // Geometry
  16828. if (source._geometry) {
  16829. source._geometry.applyToMesh(this);
  16830. }
  16831. // Deep copy
  16832. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16833. // Pivot
  16834. this.setPivotMatrix(source.getPivotMatrix());
  16835. this.id = name + "." + source.id;
  16836. // Material
  16837. this.material = source.material;
  16838. var index;
  16839. if (!doNotCloneChildren) {
  16840. // Children
  16841. for (index = 0; index < scene.meshes.length; index++) {
  16842. var mesh = scene.meshes[index];
  16843. if (mesh.parent === source) {
  16844. // doNotCloneChildren is always going to be False
  16845. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16846. }
  16847. }
  16848. }
  16849. // Physics clone
  16850. var physicsEngine = this.getScene().getPhysicsEngine();
  16851. if (clonePhysicsImpostor && physicsEngine) {
  16852. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16853. if (impostor) {
  16854. this.physicsImpostor = impostor.clone(this);
  16855. }
  16856. }
  16857. // Particles
  16858. for (index = 0; index < scene.particleSystems.length; index++) {
  16859. var system = scene.particleSystems[index];
  16860. if (system.emitter === source) {
  16861. system.clone(system.name, this);
  16862. }
  16863. }
  16864. this.computeWorldMatrix(true);
  16865. }
  16866. // Parent
  16867. if (parent !== null) {
  16868. this.parent = parent;
  16869. }
  16870. }
  16871. Object.defineProperty(Mesh, "FRONTSIDE", {
  16872. /**
  16873. * Mesh side orientation : usually the external or front surface
  16874. */
  16875. get: function () {
  16876. return Mesh._FRONTSIDE;
  16877. },
  16878. enumerable: true,
  16879. configurable: true
  16880. });
  16881. Object.defineProperty(Mesh, "BACKSIDE", {
  16882. /**
  16883. * Mesh side orientation : usually the internal or back surface
  16884. */
  16885. get: function () {
  16886. return Mesh._BACKSIDE;
  16887. },
  16888. enumerable: true,
  16889. configurable: true
  16890. });
  16891. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16892. /**
  16893. * Mesh side orientation : both internal and external or front and back surfaces
  16894. */
  16895. get: function () {
  16896. return Mesh._DOUBLESIDE;
  16897. },
  16898. enumerable: true,
  16899. configurable: true
  16900. });
  16901. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16902. /**
  16903. * Mesh side orientation : by default, `FRONTSIDE`
  16904. */
  16905. get: function () {
  16906. return Mesh._DEFAULTSIDE;
  16907. },
  16908. enumerable: true,
  16909. configurable: true
  16910. });
  16911. Object.defineProperty(Mesh, "NO_CAP", {
  16912. /**
  16913. * Mesh cap setting : no cap
  16914. */
  16915. get: function () {
  16916. return Mesh._NO_CAP;
  16917. },
  16918. enumerable: true,
  16919. configurable: true
  16920. });
  16921. Object.defineProperty(Mesh, "CAP_START", {
  16922. /**
  16923. * Mesh cap setting : one cap at the beginning of the mesh
  16924. */
  16925. get: function () {
  16926. return Mesh._CAP_START;
  16927. },
  16928. enumerable: true,
  16929. configurable: true
  16930. });
  16931. Object.defineProperty(Mesh, "CAP_END", {
  16932. /**
  16933. * Mesh cap setting : one cap at the end of the mesh
  16934. */
  16935. get: function () {
  16936. return Mesh._CAP_END;
  16937. },
  16938. enumerable: true,
  16939. configurable: true
  16940. });
  16941. Object.defineProperty(Mesh, "CAP_ALL", {
  16942. /**
  16943. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16944. */
  16945. get: function () {
  16946. return Mesh._CAP_ALL;
  16947. },
  16948. enumerable: true,
  16949. configurable: true
  16950. });
  16951. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16952. set: function (callback) {
  16953. if (this._onBeforeDrawObserver) {
  16954. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16955. }
  16956. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16957. },
  16958. enumerable: true,
  16959. configurable: true
  16960. });
  16961. // Methods
  16962. /**
  16963. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16964. */
  16965. Mesh.prototype.toString = function (fullDetails) {
  16966. var ret = _super.prototype.toString.call(this, fullDetails);
  16967. ret += ", n vertices: " + this.getTotalVertices();
  16968. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16969. if (this.animations) {
  16970. for (var i = 0; i < this.animations.length; i++) {
  16971. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16972. }
  16973. }
  16974. if (fullDetails) {
  16975. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16976. }
  16977. return ret;
  16978. };
  16979. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16980. get: function () {
  16981. return this._LODLevels.length > 0;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Mesh.prototype._sortLODLevels = function () {
  16987. this._LODLevels.sort(function (a, b) {
  16988. if (a.distance < b.distance) {
  16989. return 1;
  16990. }
  16991. if (a.distance > b.distance) {
  16992. return -1;
  16993. }
  16994. return 0;
  16995. });
  16996. };
  16997. /**
  16998. * Add a mesh as LOD level triggered at the given distance.
  16999. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17000. * @param {number} distance - the distance from the center of the object to show this level
  17001. * @param {Mesh} mesh - the mesh to be added as LOD level
  17002. * @return {Mesh} this mesh (for chaining)
  17003. */
  17004. Mesh.prototype.addLODLevel = function (distance, mesh) {
  17005. if (mesh && mesh._masterMesh) {
  17006. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  17007. return this;
  17008. }
  17009. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  17010. this._LODLevels.push(level);
  17011. if (mesh) {
  17012. mesh._masterMesh = this;
  17013. }
  17014. this._sortLODLevels();
  17015. return this;
  17016. };
  17017. /**
  17018. * Returns the LOD level mesh at the passed distance or null if not found.
  17019. * It is related to the method `addLODLevel(distance, mesh)`.
  17020. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17021. */
  17022. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  17023. for (var index = 0; index < this._LODLevels.length; index++) {
  17024. var level = this._LODLevels[index];
  17025. if (level.distance === distance) {
  17026. return level.mesh;
  17027. }
  17028. }
  17029. return null;
  17030. };
  17031. /**
  17032. * Remove a mesh from the LOD array
  17033. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17034. * @param {Mesh} mesh - the mesh to be removed.
  17035. * @return {Mesh} this mesh (for chaining)
  17036. */
  17037. Mesh.prototype.removeLODLevel = function (mesh) {
  17038. for (var index = 0; index < this._LODLevels.length; index++) {
  17039. if (this._LODLevels[index].mesh === mesh) {
  17040. this._LODLevels.splice(index, 1);
  17041. if (mesh) {
  17042. mesh._masterMesh = null;
  17043. }
  17044. }
  17045. }
  17046. this._sortLODLevels();
  17047. return this;
  17048. };
  17049. /**
  17050. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  17051. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  17052. */
  17053. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  17054. if (!this._LODLevels || this._LODLevels.length === 0) {
  17055. return this;
  17056. }
  17057. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  17058. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  17059. if (this.onLODLevelSelection) {
  17060. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  17061. }
  17062. return this;
  17063. }
  17064. for (var index = 0; index < this._LODLevels.length; index++) {
  17065. var level = this._LODLevels[index];
  17066. if (level.distance < distanceToCamera) {
  17067. if (level.mesh) {
  17068. level.mesh._preActivate();
  17069. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17070. }
  17071. if (this.onLODLevelSelection) {
  17072. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  17073. }
  17074. return level.mesh;
  17075. }
  17076. }
  17077. if (this.onLODLevelSelection) {
  17078. this.onLODLevelSelection(distanceToCamera, this, this);
  17079. }
  17080. return this;
  17081. };
  17082. Object.defineProperty(Mesh.prototype, "geometry", {
  17083. /**
  17084. * Returns the mesh internal `Geometry` object.
  17085. */
  17086. get: function () {
  17087. return this._geometry;
  17088. },
  17089. enumerable: true,
  17090. configurable: true
  17091. });
  17092. /**
  17093. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17094. */
  17095. Mesh.prototype.getTotalVertices = function () {
  17096. if (!this._geometry) {
  17097. return 0;
  17098. }
  17099. return this._geometry.getTotalVertices();
  17100. };
  17101. /**
  17102. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17103. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17104. * Returns null if the mesh has no geometry or no vertex buffer.
  17105. * Possible `kind` values :
  17106. * - BABYLON.VertexBuffer.PositionKind
  17107. * - BABYLON.VertexBuffer.UVKind
  17108. * - BABYLON.VertexBuffer.UV2Kind
  17109. * - BABYLON.VertexBuffer.UV3Kind
  17110. * - BABYLON.VertexBuffer.UV4Kind
  17111. * - BABYLON.VertexBuffer.UV5Kind
  17112. * - BABYLON.VertexBuffer.UV6Kind
  17113. * - BABYLON.VertexBuffer.ColorKind
  17114. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17115. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17116. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17117. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17118. */
  17119. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17120. if (!this._geometry) {
  17121. return null;
  17122. }
  17123. return this._geometry.getVerticesData(kind, copyWhenShared);
  17124. };
  17125. /**
  17126. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17127. * Returns `undefined` if the mesh has no geometry.
  17128. * Possible `kind` values :
  17129. * - BABYLON.VertexBuffer.PositionKind
  17130. * - BABYLON.VertexBuffer.UVKind
  17131. * - BABYLON.VertexBuffer.UV2Kind
  17132. * - BABYLON.VertexBuffer.UV3Kind
  17133. * - BABYLON.VertexBuffer.UV4Kind
  17134. * - BABYLON.VertexBuffer.UV5Kind
  17135. * - BABYLON.VertexBuffer.UV6Kind
  17136. * - BABYLON.VertexBuffer.ColorKind
  17137. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17138. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17139. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17140. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17141. */
  17142. Mesh.prototype.getVertexBuffer = function (kind) {
  17143. if (!this._geometry) {
  17144. return undefined;
  17145. }
  17146. return this._geometry.getVertexBuffer(kind);
  17147. };
  17148. /**
  17149. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17150. * Possible `kind` values :
  17151. * - BABYLON.VertexBuffer.PositionKind
  17152. * - BABYLON.VertexBuffer.UVKind
  17153. * - BABYLON.VertexBuffer.UV2Kind
  17154. * - BABYLON.VertexBuffer.UV3Kind
  17155. * - BABYLON.VertexBuffer.UV4Kind
  17156. * - BABYLON.VertexBuffer.UV5Kind
  17157. * - BABYLON.VertexBuffer.UV6Kind
  17158. * - BABYLON.VertexBuffer.ColorKind
  17159. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17160. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17161. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17162. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17163. */
  17164. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17165. if (!this._geometry) {
  17166. if (this._delayInfo) {
  17167. return this._delayInfo.indexOf(kind) !== -1;
  17168. }
  17169. return false;
  17170. }
  17171. return this._geometry.isVerticesDataPresent(kind);
  17172. };
  17173. /**
  17174. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17175. * Possible `kind` values :
  17176. * - BABYLON.VertexBuffer.PositionKind
  17177. * - BABYLON.VertexBuffer.UVKind
  17178. * - BABYLON.VertexBuffer.UV2Kind
  17179. * - BABYLON.VertexBuffer.UV3Kind
  17180. * - BABYLON.VertexBuffer.UV4Kind
  17181. * - BABYLON.VertexBuffer.UV5Kind
  17182. * - BABYLON.VertexBuffer.UV6Kind
  17183. * - BABYLON.VertexBuffer.ColorKind
  17184. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17185. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17186. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17187. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17188. */
  17189. Mesh.prototype.getVerticesDataKinds = function () {
  17190. if (!this._geometry) {
  17191. var result = [];
  17192. if (this._delayInfo) {
  17193. for (var kind in this._delayInfo) {
  17194. result.push(kind);
  17195. }
  17196. }
  17197. return result;
  17198. }
  17199. return this._geometry.getVerticesDataKinds();
  17200. };
  17201. /**
  17202. * Returns a positive integer : the total number of indices in this mesh geometry.
  17203. * Returns zero if the mesh has no geometry.
  17204. */
  17205. Mesh.prototype.getTotalIndices = function () {
  17206. if (!this._geometry) {
  17207. return 0;
  17208. }
  17209. return this._geometry.getTotalIndices();
  17210. };
  17211. /**
  17212. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17213. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  17214. * Returns an empty array if the mesh has no geometry.
  17215. */
  17216. Mesh.prototype.getIndices = function (copyWhenShared) {
  17217. if (!this._geometry) {
  17218. return [];
  17219. }
  17220. return this._geometry.getIndices(copyWhenShared);
  17221. };
  17222. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17223. get: function () {
  17224. return this._masterMesh !== null && this._masterMesh !== undefined;
  17225. },
  17226. enumerable: true,
  17227. configurable: true
  17228. });
  17229. /**
  17230. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17231. */
  17232. Mesh.prototype.isReady = function () {
  17233. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17234. return false;
  17235. }
  17236. return _super.prototype.isReady.call(this);
  17237. };
  17238. /**
  17239. * Boolean : true if the mesh has been disposed.
  17240. */
  17241. Mesh.prototype.isDisposed = function () {
  17242. return this._isDisposed;
  17243. };
  17244. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17245. get: function () {
  17246. return this._sideOrientation;
  17247. },
  17248. /**
  17249. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17250. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17251. */
  17252. set: function (sideO) {
  17253. this._sideOrientation = sideO;
  17254. },
  17255. enumerable: true,
  17256. configurable: true
  17257. });
  17258. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17259. /**
  17260. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17261. * This property is pertinent only for updatable parametric shapes.
  17262. */
  17263. get: function () {
  17264. return this._areNormalsFrozen;
  17265. },
  17266. enumerable: true,
  17267. configurable: true
  17268. });
  17269. /**
  17270. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17271. * It has no effect at all on other shapes.
  17272. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17273. */
  17274. Mesh.prototype.freezeNormals = function () {
  17275. this._areNormalsFrozen = true;
  17276. };
  17277. /**
  17278. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17279. * It has no effect at all on other shapes.
  17280. * It reactivates the mesh normals computation if it was previously frozen.
  17281. */
  17282. Mesh.prototype.unfreezeNormals = function () {
  17283. this._areNormalsFrozen = false;
  17284. };
  17285. // Methods
  17286. Mesh.prototype._preActivate = function () {
  17287. var sceneRenderId = this.getScene().getRenderId();
  17288. if (this._preActivateId === sceneRenderId) {
  17289. return;
  17290. }
  17291. this._preActivateId = sceneRenderId;
  17292. this._visibleInstances = null;
  17293. };
  17294. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17295. if (this._visibleInstances) {
  17296. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17297. }
  17298. };
  17299. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17300. if (!this._visibleInstances) {
  17301. this._visibleInstances = {};
  17302. this._visibleInstances.defaultRenderId = renderId;
  17303. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17304. }
  17305. if (!this._visibleInstances[renderId]) {
  17306. this._visibleInstances[renderId] = new Array();
  17307. }
  17308. this._visibleInstances[renderId].push(instance);
  17309. };
  17310. /**
  17311. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17312. * This means the mesh underlying bounding box and sphere are recomputed.
  17313. */
  17314. Mesh.prototype.refreshBoundingInfo = function () {
  17315. if (this._boundingInfo.isLocked) {
  17316. return;
  17317. }
  17318. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17319. if (data) {
  17320. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17321. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17322. }
  17323. if (this.subMeshes) {
  17324. for (var index = 0; index < this.subMeshes.length; index++) {
  17325. this.subMeshes[index].refreshBoundingInfo();
  17326. }
  17327. }
  17328. this._updateBoundingInfo();
  17329. };
  17330. Mesh.prototype._createGlobalSubMesh = function () {
  17331. var totalVertices = this.getTotalVertices();
  17332. if (!totalVertices || !this.getIndices()) {
  17333. return null;
  17334. }
  17335. this.releaseSubMeshes();
  17336. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17337. };
  17338. Mesh.prototype.subdivide = function (count) {
  17339. if (count < 1) {
  17340. return;
  17341. }
  17342. var totalIndices = this.getTotalIndices();
  17343. var subdivisionSize = (totalIndices / count) | 0;
  17344. var offset = 0;
  17345. // Ensure that subdivisionSize is a multiple of 3
  17346. while (subdivisionSize % 3 !== 0) {
  17347. subdivisionSize++;
  17348. }
  17349. this.releaseSubMeshes();
  17350. for (var index = 0; index < count; index++) {
  17351. if (offset >= totalIndices) {
  17352. break;
  17353. }
  17354. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17355. offset += subdivisionSize;
  17356. }
  17357. this.synchronizeInstances();
  17358. };
  17359. /**
  17360. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17361. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17362. * The `data` are either a numeric array either a Float32Array.
  17363. * The parameter `updatable` is passed as is to the underlying `Geometry` object constructor (if initianilly none) or updater.
  17364. * 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).
  17365. * Note that a new underlying `VertexBuffer` object is created each call.
  17366. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17367. *
  17368. * Possible `kind` values :
  17369. * - BABYLON.VertexBuffer.PositionKind
  17370. * - BABYLON.VertexBuffer.UVKind
  17371. * - BABYLON.VertexBuffer.UV2Kind
  17372. * - BABYLON.VertexBuffer.UV3Kind
  17373. * - BABYLON.VertexBuffer.UV4Kind
  17374. * - BABYLON.VertexBuffer.UV5Kind
  17375. * - BABYLON.VertexBuffer.UV6Kind
  17376. * - BABYLON.VertexBuffer.ColorKind
  17377. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17378. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17379. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17380. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17381. */
  17382. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17383. if (!this._geometry) {
  17384. var vertexData = new BABYLON.VertexData();
  17385. vertexData.set(data, kind);
  17386. var scene = this.getScene();
  17387. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17388. }
  17389. else {
  17390. this._geometry.setVerticesData(kind, data, updatable, stride);
  17391. }
  17392. };
  17393. /**
  17394. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17395. * If the mesh has no geometry, it is simply returned as it is.
  17396. * The `data` are either a numeric array either a Float32Array.
  17397. * No new underlying `VertexBuffer` object is created.
  17398. * 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.
  17399. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17400. *
  17401. * Possible `kind` values :
  17402. * - BABYLON.VertexBuffer.PositionKind
  17403. * - BABYLON.VertexBuffer.UVKind
  17404. * - BABYLON.VertexBuffer.UV2Kind
  17405. * - BABYLON.VertexBuffer.UV3Kind
  17406. * - BABYLON.VertexBuffer.UV4Kind
  17407. * - BABYLON.VertexBuffer.UV5Kind
  17408. * - BABYLON.VertexBuffer.UV6Kind
  17409. * - BABYLON.VertexBuffer.ColorKind
  17410. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17411. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17412. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17413. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17414. */
  17415. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17416. if (!this._geometry) {
  17417. return;
  17418. }
  17419. if (!makeItUnique) {
  17420. this._geometry.updateVerticesData(kind, data, updateExtends);
  17421. }
  17422. else {
  17423. this.makeGeometryUnique();
  17424. this.updateVerticesData(kind, data, updateExtends, false);
  17425. }
  17426. };
  17427. /**
  17428. * Deprecated since BabylonJS v2.3
  17429. */
  17430. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17431. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17432. if (!this._geometry) {
  17433. return;
  17434. }
  17435. if (!makeItUnique) {
  17436. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17437. }
  17438. else {
  17439. this.makeGeometryUnique();
  17440. this.updateVerticesDataDirectly(kind, data, offset, false);
  17441. }
  17442. };
  17443. /**
  17444. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17445. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17446. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17447. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17448. */
  17449. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17450. if (computeNormals === void 0) { computeNormals = true; }
  17451. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17452. positionFunction(positions);
  17453. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17454. if (computeNormals) {
  17455. var indices = this.getIndices();
  17456. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17457. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17458. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17459. }
  17460. };
  17461. Mesh.prototype.makeGeometryUnique = function () {
  17462. if (!this._geometry) {
  17463. return;
  17464. }
  17465. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17466. geometry.applyToMesh(this);
  17467. };
  17468. /**
  17469. * Sets the mesh indices.
  17470. * Expects an array populated with integers or a Int32Array.
  17471. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17472. * This method creates a new index buffer each call.
  17473. */
  17474. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17475. if (!this._geometry) {
  17476. var vertexData = new BABYLON.VertexData();
  17477. vertexData.indices = indices;
  17478. var scene = this.getScene();
  17479. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17480. }
  17481. else {
  17482. this._geometry.setIndices(indices, totalVertices);
  17483. }
  17484. };
  17485. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17486. var engine = this.getScene().getEngine();
  17487. // Wireframe
  17488. var indexToBind;
  17489. if (this._unIndexed) {
  17490. indexToBind = null;
  17491. }
  17492. else {
  17493. switch (fillMode) {
  17494. case BABYLON.Material.PointFillMode:
  17495. indexToBind = null;
  17496. break;
  17497. case BABYLON.Material.WireFrameFillMode:
  17498. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17499. break;
  17500. default:
  17501. case BABYLON.Material.TriangleFillMode:
  17502. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17503. break;
  17504. }
  17505. }
  17506. // VBOs
  17507. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17508. };
  17509. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17510. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17511. return;
  17512. }
  17513. this.onBeforeDrawObservable.notifyObservers(this);
  17514. var engine = this.getScene().getEngine();
  17515. // Draw order
  17516. switch (fillMode) {
  17517. case BABYLON.Material.PointFillMode:
  17518. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17519. break;
  17520. case BABYLON.Material.WireFrameFillMode:
  17521. if (this._unIndexed) {
  17522. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17523. }
  17524. else {
  17525. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17526. }
  17527. break;
  17528. default:
  17529. if (this._unIndexed) {
  17530. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17531. }
  17532. else {
  17533. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17534. }
  17535. }
  17536. };
  17537. /**
  17538. * Registers for this mesh a javascript function called just before the rendering process.
  17539. * This function is passed the current mesh and doesn't return anything.
  17540. */
  17541. Mesh.prototype.registerBeforeRender = function (func) {
  17542. this.onBeforeRenderObservable.add(func);
  17543. };
  17544. /**
  17545. * Disposes a previously registered javascript function called before the rendering.
  17546. * This function is passed the current mesh and doesn't return anything.
  17547. */
  17548. Mesh.prototype.unregisterBeforeRender = function (func) {
  17549. this.onBeforeRenderObservable.removeCallback(func);
  17550. };
  17551. /**
  17552. * Registers for this mesh a javascript function called just after the rendering is complete.
  17553. * This function is passed the current mesh and doesn't return anything.
  17554. */
  17555. Mesh.prototype.registerAfterRender = function (func) {
  17556. this.onAfterRenderObservable.add(func);
  17557. };
  17558. /**
  17559. * Disposes a previously registered javascript function called after the rendering.
  17560. * This function is passed the current mesh and doesn't return anything.
  17561. */
  17562. Mesh.prototype.unregisterAfterRender = function (func) {
  17563. this.onAfterRenderObservable.removeCallback(func);
  17564. };
  17565. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17566. var scene = this.getScene();
  17567. this._batchCache.mustReturn = false;
  17568. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17569. this._batchCache.visibleInstances[subMeshId] = null;
  17570. if (this._visibleInstances) {
  17571. var currentRenderId = scene.getRenderId();
  17572. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17573. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17574. var selfRenderId = this._renderId;
  17575. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17576. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17577. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17578. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17579. }
  17580. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17581. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17582. this._batchCache.mustReturn = true;
  17583. return this._batchCache;
  17584. }
  17585. if (currentRenderId !== selfRenderId) {
  17586. this._batchCache.renderSelf[subMeshId] = false;
  17587. }
  17588. }
  17589. this._renderIdForInstances[subMeshId] = currentRenderId;
  17590. }
  17591. return this._batchCache;
  17592. };
  17593. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17594. var visibleInstances = batch.visibleInstances[subMesh._id];
  17595. var matricesCount = visibleInstances.length + 1;
  17596. var bufferSize = matricesCount * 16 * 4;
  17597. while (this._instancesBufferSize < bufferSize) {
  17598. this._instancesBufferSize *= 2;
  17599. }
  17600. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17601. if (this._worldMatricesInstancesBuffer) {
  17602. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17603. }
  17604. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17605. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17606. }
  17607. var offset = 0;
  17608. var instancesCount = 0;
  17609. var world = this.getWorldMatrix();
  17610. if (batch.renderSelf[subMesh._id]) {
  17611. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17612. offset += 16;
  17613. instancesCount++;
  17614. }
  17615. if (visibleInstances) {
  17616. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17617. var instance = visibleInstances[instanceIndex];
  17618. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17619. offset += 16;
  17620. instancesCount++;
  17621. }
  17622. }
  17623. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17624. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17625. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17626. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17627. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17628. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17629. this._draw(subMesh, fillMode, instancesCount);
  17630. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17631. };
  17632. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17633. var scene = this.getScene();
  17634. var engine = scene.getEngine();
  17635. if (hardwareInstancedRendering) {
  17636. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17637. }
  17638. else {
  17639. if (batch.renderSelf[subMesh._id]) {
  17640. // Draw
  17641. if (onBeforeDraw) {
  17642. onBeforeDraw(false, this.getWorldMatrix());
  17643. }
  17644. this._draw(subMesh, fillMode);
  17645. }
  17646. if (batch.visibleInstances[subMesh._id]) {
  17647. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17648. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17649. // World
  17650. var world = instance.getWorldMatrix();
  17651. if (onBeforeDraw) {
  17652. onBeforeDraw(true, world);
  17653. }
  17654. // Draw
  17655. this._draw(subMesh, fillMode);
  17656. }
  17657. }
  17658. }
  17659. };
  17660. /**
  17661. * Triggers the draw call for the mesh.
  17662. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  17663. */
  17664. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17665. var scene = this.getScene();
  17666. // Managing instances
  17667. var batch = this._getInstancesRenderList(subMesh._id);
  17668. if (batch.mustReturn) {
  17669. return;
  17670. }
  17671. // Checking geometry state
  17672. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17673. return;
  17674. }
  17675. var callbackIndex;
  17676. this.onBeforeRenderObservable.notifyObservers(this);
  17677. var engine = scene.getEngine();
  17678. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17679. // Material
  17680. var effectiveMaterial = subMesh.getMaterial();
  17681. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17682. return;
  17683. }
  17684. // Outline - step 1
  17685. var savedDepthWrite = engine.getDepthWrite();
  17686. if (this.renderOutline) {
  17687. engine.setDepthWrite(false);
  17688. scene.getOutlineRenderer().render(subMesh, batch);
  17689. engine.setDepthWrite(savedDepthWrite);
  17690. }
  17691. effectiveMaterial._preBind();
  17692. var effect = effectiveMaterial.getEffect();
  17693. // Bind
  17694. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17695. this._bind(subMesh, effect, fillMode);
  17696. var world = this.getWorldMatrix();
  17697. effectiveMaterial.bind(world, this);
  17698. // Alpha mode
  17699. if (enableAlphaMode) {
  17700. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17701. }
  17702. // Draw
  17703. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17704. if (isInstance) {
  17705. effectiveMaterial.bindOnlyWorldMatrix(world);
  17706. }
  17707. });
  17708. // Unbind
  17709. effectiveMaterial.unbind();
  17710. // Outline - step 2
  17711. if (this.renderOutline && savedDepthWrite) {
  17712. engine.setDepthWrite(true);
  17713. engine.setColorWrite(false);
  17714. scene.getOutlineRenderer().render(subMesh, batch);
  17715. engine.setColorWrite(true);
  17716. }
  17717. // Overlay
  17718. if (this.renderOverlay) {
  17719. var currentMode = engine.getAlphaMode();
  17720. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17721. scene.getOutlineRenderer().render(subMesh, batch, true);
  17722. engine.setAlphaMode(currentMode);
  17723. }
  17724. this.onAfterRenderObservable.notifyObservers(this);
  17725. };
  17726. /**
  17727. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17728. */
  17729. Mesh.prototype.getEmittedParticleSystems = function () {
  17730. var results = new Array();
  17731. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17732. var particleSystem = this.getScene().particleSystems[index];
  17733. if (particleSystem.emitter === this) {
  17734. results.push(particleSystem);
  17735. }
  17736. }
  17737. return results;
  17738. };
  17739. /**
  17740. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17741. */
  17742. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17743. var results = new Array();
  17744. var descendants = this.getDescendants();
  17745. descendants.push(this);
  17746. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17747. var particleSystem = this.getScene().particleSystems[index];
  17748. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17749. results.push(particleSystem);
  17750. }
  17751. }
  17752. return results;
  17753. };
  17754. Mesh.prototype._checkDelayState = function () {
  17755. var _this = this;
  17756. var that = this;
  17757. var scene = this.getScene();
  17758. if (this._geometry) {
  17759. this._geometry.load(scene);
  17760. }
  17761. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17762. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17763. scene._addPendingData(that);
  17764. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17765. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17766. if (data instanceof ArrayBuffer) {
  17767. _this._delayLoadingFunction(data, _this);
  17768. }
  17769. else {
  17770. _this._delayLoadingFunction(JSON.parse(data), _this);
  17771. }
  17772. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17773. scene._removePendingData(_this);
  17774. }, function () { }, scene.database, getBinaryData);
  17775. }
  17776. };
  17777. /**
  17778. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17779. */
  17780. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17781. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17782. return false;
  17783. }
  17784. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17785. return false;
  17786. }
  17787. this._checkDelayState();
  17788. return true;
  17789. };
  17790. /**
  17791. * Sets the mesh material by the material or multiMaterial `id` property.
  17792. * The material `id` is a string identifying the material or the multiMaterial.
  17793. * This method returns nothing.
  17794. */
  17795. Mesh.prototype.setMaterialByID = function (id) {
  17796. var materials = this.getScene().materials;
  17797. var index;
  17798. for (index = 0; index < materials.length; index++) {
  17799. if (materials[index].id === id) {
  17800. this.material = materials[index];
  17801. return;
  17802. }
  17803. }
  17804. // Multi
  17805. var multiMaterials = this.getScene().multiMaterials;
  17806. for (index = 0; index < multiMaterials.length; index++) {
  17807. if (multiMaterials[index].id === id) {
  17808. this.material = multiMaterials[index];
  17809. return;
  17810. }
  17811. }
  17812. };
  17813. /**
  17814. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  17815. */
  17816. Mesh.prototype.getAnimatables = function () {
  17817. var results = [];
  17818. if (this.material) {
  17819. results.push(this.material);
  17820. }
  17821. if (this.skeleton) {
  17822. results.push(this.skeleton);
  17823. }
  17824. return results;
  17825. };
  17826. /**
  17827. * Modifies the mesh geometry according to the passed transformation matrix.
  17828. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  17829. * The mesh normals are modified accordingly the same transformation.
  17830. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  17831. * Note that, under the hood, this method sets a new VertexBuffer each call.
  17832. */
  17833. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17834. // Position
  17835. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17836. return;
  17837. }
  17838. var submeshes = this.subMeshes.splice(0);
  17839. this._resetPointsArrayCache();
  17840. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17841. var temp = [];
  17842. var index;
  17843. for (index = 0; index < data.length; index += 3) {
  17844. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17845. }
  17846. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17847. // Normals
  17848. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17849. return;
  17850. }
  17851. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17852. temp = [];
  17853. for (index = 0; index < data.length; index += 3) {
  17854. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17855. }
  17856. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17857. // flip faces?
  17858. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17859. this.flipFaces();
  17860. }
  17861. // Restore submeshes
  17862. this.releaseSubMeshes();
  17863. this.subMeshes = submeshes;
  17864. };
  17865. /**
  17866. * Modifies the mesh geometry according to its own current World Matrix.
  17867. * The mesh World Matrix is then reset.
  17868. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  17869. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  17870. * Note that, under the hood, this method sets a new VertexBuffer each call.
  17871. */
  17872. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17873. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17874. this.scaling.copyFromFloats(1, 1, 1);
  17875. this.position.copyFromFloats(0, 0, 0);
  17876. this.rotation.copyFromFloats(0, 0, 0);
  17877. //only if quaternion is already set
  17878. if (this.rotationQuaternion) {
  17879. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17880. }
  17881. this._worldMatrix = BABYLON.Matrix.Identity();
  17882. };
  17883. // Cache
  17884. Mesh.prototype._resetPointsArrayCache = function () {
  17885. this._positions = null;
  17886. };
  17887. Mesh.prototype._generatePointsArray = function () {
  17888. if (this._positions)
  17889. return true;
  17890. this._positions = [];
  17891. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17892. if (!data) {
  17893. return false;
  17894. }
  17895. for (var index = 0; index < data.length; index += 3) {
  17896. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17897. }
  17898. return true;
  17899. };
  17900. /**
  17901. * Returns a new `Mesh` object generated from the current mesh properties.
  17902. * This method must not get confused with createInstance().
  17903. * The parameter `name` is a string, the name given to the new mesh.
  17904. * The optional parameter `newParent` can be any `Node` object (default `null`).
  17905. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  17906. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  17907. */
  17908. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17909. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17910. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17911. };
  17912. /**
  17913. * Disposes the mesh.
  17914. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  17915. */
  17916. Mesh.prototype.dispose = function (doNotRecurse) {
  17917. if (this._geometry) {
  17918. this._geometry.releaseForMesh(this, true);
  17919. }
  17920. // Instances
  17921. if (this._worldMatricesInstancesBuffer) {
  17922. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17923. this._worldMatricesInstancesBuffer = null;
  17924. }
  17925. while (this.instances.length) {
  17926. this.instances[0].dispose();
  17927. }
  17928. _super.prototype.dispose.call(this, doNotRecurse);
  17929. };
  17930. /**
  17931. * Modifies the mesh geometry according to a displacement map.
  17932. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  17933. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  17934. * This method returns nothing.
  17935. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  17936. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  17937. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  17938. */
  17939. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17940. var _this = this;
  17941. var scene = this.getScene();
  17942. var onload = function (img) {
  17943. // Getting height map data
  17944. var canvas = document.createElement("canvas");
  17945. var context = canvas.getContext("2d");
  17946. var heightMapWidth = img.width;
  17947. var heightMapHeight = img.height;
  17948. canvas.width = heightMapWidth;
  17949. canvas.height = heightMapHeight;
  17950. context.drawImage(img, 0, 0);
  17951. // Create VertexData from map data
  17952. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17953. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17954. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17955. //execute success callback, if set
  17956. if (onSuccess) {
  17957. onSuccess(_this);
  17958. }
  17959. };
  17960. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17961. };
  17962. /**
  17963. * Modifies the mesh geometry according to a displacementMap buffer.
  17964. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  17965. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  17966. * This method returns nothing.
  17967. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  17968. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  17969. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  17970. */
  17971. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17972. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17973. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17974. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17975. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17976. return;
  17977. }
  17978. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17979. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17980. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17981. var position = BABYLON.Vector3.Zero();
  17982. var normal = BABYLON.Vector3.Zero();
  17983. var uv = BABYLON.Vector2.Zero();
  17984. for (var index = 0; index < positions.length; index += 3) {
  17985. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17986. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17987. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17988. // Compute height
  17989. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17990. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17991. var pos = (u + v * heightMapWidth) * 4;
  17992. var r = buffer[pos] / 255.0;
  17993. var g = buffer[pos + 1] / 255.0;
  17994. var b = buffer[pos + 2] / 255.0;
  17995. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17996. normal.normalize();
  17997. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17998. position = position.add(normal);
  17999. position.toArray(positions, index);
  18000. }
  18001. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  18002. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  18003. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18004. };
  18005. /**
  18006. * Modify the mesh to get a flat shading rendering.
  18007. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  18008. * This method returns nothing.
  18009. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  18010. */
  18011. Mesh.prototype.convertToFlatShadedMesh = function () {
  18012. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  18013. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18014. var kinds = this.getVerticesDataKinds();
  18015. var vbs = [];
  18016. var data = [];
  18017. var newdata = [];
  18018. var updatableNormals = false;
  18019. var kindIndex;
  18020. var kind;
  18021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18022. kind = kinds[kindIndex];
  18023. var vertexBuffer = this.getVertexBuffer(kind);
  18024. if (kind === BABYLON.VertexBuffer.NormalKind) {
  18025. updatableNormals = vertexBuffer.isUpdatable();
  18026. kinds.splice(kindIndex, 1);
  18027. kindIndex--;
  18028. continue;
  18029. }
  18030. vbs[kind] = vertexBuffer;
  18031. data[kind] = vbs[kind].getData();
  18032. newdata[kind] = [];
  18033. }
  18034. // Save previous submeshes
  18035. var previousSubmeshes = this.subMeshes.slice(0);
  18036. var indices = this.getIndices();
  18037. var totalIndices = this.getTotalIndices();
  18038. // Generating unique vertices per face
  18039. var index;
  18040. for (index = 0; index < totalIndices; index++) {
  18041. var vertexIndex = indices[index];
  18042. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18043. kind = kinds[kindIndex];
  18044. var stride = vbs[kind].getStrideSize();
  18045. for (var offset = 0; offset < stride; offset++) {
  18046. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18047. }
  18048. }
  18049. }
  18050. // Updating faces & normal
  18051. var normals = [];
  18052. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  18053. for (index = 0; index < totalIndices; index += 3) {
  18054. indices[index] = index;
  18055. indices[index + 1] = index + 1;
  18056. indices[index + 2] = index + 2;
  18057. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  18058. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  18059. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  18060. var p1p2 = p1.subtract(p2);
  18061. var p3p2 = p3.subtract(p2);
  18062. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  18063. // Store same normals for every vertex
  18064. for (var localIndex = 0; localIndex < 3; localIndex++) {
  18065. normals.push(normal.x);
  18066. normals.push(normal.y);
  18067. normals.push(normal.z);
  18068. }
  18069. }
  18070. this.setIndices(indices);
  18071. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  18072. // Updating vertex buffers
  18073. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18074. kind = kinds[kindIndex];
  18075. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18076. }
  18077. // Updating submeshes
  18078. this.releaseSubMeshes();
  18079. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18080. var previousOne = previousSubmeshes[submeshIndex];
  18081. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18082. }
  18083. this.synchronizeInstances();
  18084. };
  18085. /**
  18086. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  18087. * In other words, more vertices, no more indices and a single bigger VBO.
  18088. * This method returns nothing.
  18089. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  18090. *
  18091. */
  18092. Mesh.prototype.convertToUnIndexedMesh = function () {
  18093. /// <summary>Remove indices by unfolding faces into buffers</summary>
  18094. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  18095. var kinds = this.getVerticesDataKinds();
  18096. var vbs = [];
  18097. var data = [];
  18098. var newdata = [];
  18099. var updatableNormals = false;
  18100. var kindIndex;
  18101. var kind;
  18102. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18103. kind = kinds[kindIndex];
  18104. var vertexBuffer = this.getVertexBuffer(kind);
  18105. vbs[kind] = vertexBuffer;
  18106. data[kind] = vbs[kind].getData();
  18107. newdata[kind] = [];
  18108. }
  18109. // Save previous submeshes
  18110. var previousSubmeshes = this.subMeshes.slice(0);
  18111. var indices = this.getIndices();
  18112. var totalIndices = this.getTotalIndices();
  18113. // Generating unique vertices per face
  18114. var index;
  18115. for (index = 0; index < totalIndices; index++) {
  18116. var vertexIndex = indices[index];
  18117. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18118. kind = kinds[kindIndex];
  18119. var stride = vbs[kind].getStrideSize();
  18120. for (var offset = 0; offset < stride; offset++) {
  18121. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  18122. }
  18123. }
  18124. }
  18125. // Updating indices
  18126. for (index = 0; index < totalIndices; index += 3) {
  18127. indices[index] = index;
  18128. indices[index + 1] = index + 1;
  18129. indices[index + 2] = index + 2;
  18130. }
  18131. this.setIndices(indices);
  18132. // Updating vertex buffers
  18133. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  18134. kind = kinds[kindIndex];
  18135. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  18136. }
  18137. // Updating submeshes
  18138. this.releaseSubMeshes();
  18139. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  18140. var previousOne = previousSubmeshes[submeshIndex];
  18141. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  18142. }
  18143. this._unIndexed = true;
  18144. this.synchronizeInstances();
  18145. };
  18146. /**
  18147. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  18148. * This method returns nothing.
  18149. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  18150. */
  18151. Mesh.prototype.flipFaces = function (flipNormals) {
  18152. if (flipNormals === void 0) { flipNormals = false; }
  18153. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18154. var i;
  18155. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18156. for (i = 0; i < vertex_data.normals.length; i++) {
  18157. vertex_data.normals[i] *= -1;
  18158. }
  18159. }
  18160. var temp;
  18161. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18162. // reassign indices
  18163. temp = vertex_data.indices[i + 1];
  18164. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18165. vertex_data.indices[i + 2] = temp;
  18166. }
  18167. vertex_data.applyToMesh(this);
  18168. };
  18169. // Instances
  18170. /**
  18171. * Creates a new `InstancedMesh` object from the mesh model.
  18172. * An instance shares the same properties and the same material than its model.
  18173. * Only these properties of each instance can then be set individually :
  18174. * - position
  18175. * - rotation
  18176. * - rotationQuaternion
  18177. * - setPivotMatrix
  18178. * - scaling
  18179. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  18180. * Warning : this method is not supported for `Line` mesh and `LineSystem`
  18181. */
  18182. Mesh.prototype.createInstance = function (name) {
  18183. return new BABYLON.InstancedMesh(name, this);
  18184. };
  18185. /**
  18186. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  18187. * After this call, all the mesh instances have the same submeshes than the current mesh.
  18188. * This method returns nothing.
  18189. */
  18190. Mesh.prototype.synchronizeInstances = function () {
  18191. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18192. var instance = this.instances[instanceIndex];
  18193. instance._syncSubMeshes();
  18194. }
  18195. };
  18196. /**
  18197. * Simplify the mesh according to the given array of settings.
  18198. * Function will return immediately and will simplify async. It returns nothing.
  18199. * @param settings a collection of simplification settings.
  18200. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18201. * @param type the type of simplification to run.
  18202. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18203. */
  18204. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18205. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18206. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18207. this.getScene().simplificationQueue.addTask({
  18208. settings: settings,
  18209. parallelProcessing: parallelProcessing,
  18210. mesh: this,
  18211. simplificationType: simplificationType,
  18212. successCallback: successCallback
  18213. });
  18214. };
  18215. /**
  18216. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18217. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18218. * This should be used together with the simplification to avoid disappearing triangles.
  18219. * @param successCallback an optional success callback to be called after the optimization finished.
  18220. */
  18221. Mesh.prototype.optimizeIndices = function (successCallback) {
  18222. var _this = this;
  18223. var indices = this.getIndices();
  18224. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18225. var vectorPositions = [];
  18226. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18227. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18228. }
  18229. var dupes = [];
  18230. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18231. var realPos = vectorPositions.length - 1 - iteration;
  18232. var testedPosition = vectorPositions[realPos];
  18233. for (var j = 0; j < realPos; ++j) {
  18234. var againstPosition = vectorPositions[j];
  18235. if (testedPosition.equals(againstPosition)) {
  18236. dupes[realPos] = j;
  18237. break;
  18238. }
  18239. }
  18240. }, function () {
  18241. for (var i = 0; i < indices.length; ++i) {
  18242. indices[i] = dupes[indices[i]] || indices[i];
  18243. }
  18244. //indices are now reordered
  18245. var originalSubMeshes = _this.subMeshes.slice(0);
  18246. _this.setIndices(indices);
  18247. _this.subMeshes = originalSubMeshes;
  18248. if (successCallback) {
  18249. successCallback(_this);
  18250. }
  18251. });
  18252. };
  18253. // Statics
  18254. /**
  18255. * Returns a new `Mesh` object what is a deep copy of the passed mesh.
  18256. * The parameter `parsedMesh` is the mesh to be copied.
  18257. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18258. */
  18259. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18260. var mesh = new Mesh(parsedMesh.name, scene);
  18261. mesh.id = parsedMesh.id;
  18262. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18263. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18264. if (parsedMesh.rotationQuaternion) {
  18265. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18266. }
  18267. else if (parsedMesh.rotation) {
  18268. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18269. }
  18270. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18271. if (parsedMesh.localMatrix) {
  18272. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18273. }
  18274. else if (parsedMesh.pivotMatrix) {
  18275. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18276. }
  18277. mesh.setEnabled(parsedMesh.isEnabled);
  18278. mesh.isVisible = parsedMesh.isVisible;
  18279. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18280. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18281. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18282. if (parsedMesh.applyFog !== undefined) {
  18283. mesh.applyFog = parsedMesh.applyFog;
  18284. }
  18285. if (parsedMesh.pickable !== undefined) {
  18286. mesh.isPickable = parsedMesh.pickable;
  18287. }
  18288. if (parsedMesh.alphaIndex !== undefined) {
  18289. mesh.alphaIndex = parsedMesh.alphaIndex;
  18290. }
  18291. mesh.receiveShadows = parsedMesh.receiveShadows;
  18292. mesh.billboardMode = parsedMesh.billboardMode;
  18293. if (parsedMesh.visibility !== undefined) {
  18294. mesh.visibility = parsedMesh.visibility;
  18295. }
  18296. mesh.checkCollisions = parsedMesh.checkCollisions;
  18297. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18298. // freezeWorldMatrix
  18299. if (parsedMesh.freezeWorldMatrix) {
  18300. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18301. }
  18302. // Parent
  18303. if (parsedMesh.parentId) {
  18304. mesh._waitingParentId = parsedMesh.parentId;
  18305. }
  18306. // Actions
  18307. if (parsedMesh.actions !== undefined) {
  18308. mesh._waitingActions = parsedMesh.actions;
  18309. }
  18310. // Geometry
  18311. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18312. if (parsedMesh.delayLoadingFile) {
  18313. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18314. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18315. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18316. if (parsedMesh._binaryInfo) {
  18317. mesh._binaryInfo = parsedMesh._binaryInfo;
  18318. }
  18319. mesh._delayInfo = [];
  18320. if (parsedMesh.hasUVs) {
  18321. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18322. }
  18323. if (parsedMesh.hasUVs2) {
  18324. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18325. }
  18326. if (parsedMesh.hasUVs3) {
  18327. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18328. }
  18329. if (parsedMesh.hasUVs4) {
  18330. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18331. }
  18332. if (parsedMesh.hasUVs5) {
  18333. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18334. }
  18335. if (parsedMesh.hasUVs6) {
  18336. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18337. }
  18338. if (parsedMesh.hasColors) {
  18339. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18340. }
  18341. if (parsedMesh.hasMatricesIndices) {
  18342. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18343. }
  18344. if (parsedMesh.hasMatricesWeights) {
  18345. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18346. }
  18347. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18348. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18349. mesh._checkDelayState();
  18350. }
  18351. }
  18352. else {
  18353. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18354. }
  18355. // Material
  18356. if (parsedMesh.materialId) {
  18357. mesh.setMaterialByID(parsedMesh.materialId);
  18358. }
  18359. else {
  18360. mesh.material = null;
  18361. }
  18362. // Skeleton
  18363. if (parsedMesh.skeletonId > -1) {
  18364. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18365. if (parsedMesh.numBoneInfluencers) {
  18366. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18367. }
  18368. }
  18369. // Animations
  18370. if (parsedMesh.animations) {
  18371. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18372. var parsedAnimation = parsedMesh.animations[animationIndex];
  18373. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18374. }
  18375. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18376. }
  18377. if (parsedMesh.autoAnimate) {
  18378. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18379. }
  18380. // Layer Mask
  18381. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18382. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18383. }
  18384. else {
  18385. mesh.layerMask = 0x0FFFFFFF;
  18386. }
  18387. //(Deprecated) physics
  18388. if (parsedMesh.physicsImpostor) {
  18389. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18390. mass: parsedMesh.physicsMass,
  18391. friction: parsedMesh.physicsFriction,
  18392. restitution: parsedMesh.physicsRestitution
  18393. }, scene);
  18394. }
  18395. // Instances
  18396. if (parsedMesh.instances) {
  18397. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18398. var parsedInstance = parsedMesh.instances[index];
  18399. var instance = mesh.createInstance(parsedInstance.name);
  18400. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18401. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18402. if (parsedInstance.rotationQuaternion) {
  18403. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18404. }
  18405. else if (parsedInstance.rotation) {
  18406. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18407. }
  18408. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18409. instance.checkCollisions = mesh.checkCollisions;
  18410. if (parsedMesh.animations) {
  18411. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18412. parsedAnimation = parsedMesh.animations[animationIndex];
  18413. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18414. }
  18415. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18416. }
  18417. }
  18418. }
  18419. return mesh;
  18420. };
  18421. /**
  18422. * Creates a ribbon mesh.
  18423. * Please consider using the same method from the `MeshBuilder` class instead.
  18424. * 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.
  18425. *
  18426. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18427. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18428. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18429. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18430. * 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.
  18431. * 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.
  18432. * 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
  18433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18434. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18436. */
  18437. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18438. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18439. pathArray: pathArray,
  18440. closeArray: closeArray,
  18441. closePath: closePath,
  18442. offset: offset,
  18443. updatable: updatable,
  18444. sideOrientation: sideOrientation,
  18445. instance: instance
  18446. }, scene);
  18447. };
  18448. /**
  18449. * Creates a plane polygonal mesh. By default, this is a disc.
  18450. * Please consider using the same method from the `MeshBuilder` class instead.
  18451. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18452. * 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.
  18453. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18454. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18456. */
  18457. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18458. var options = {
  18459. radius: radius,
  18460. tessellation: tessellation,
  18461. sideOrientation: sideOrientation,
  18462. updatable: updatable
  18463. };
  18464. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18465. };
  18466. /**
  18467. * Creates a box mesh.
  18468. * Please consider using the same method from the `MeshBuilder` class instead.
  18469. * The parameter `size` sets the size (float) of each box side (default 1).
  18470. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18471. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18473. */
  18474. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18475. var options = {
  18476. size: size,
  18477. sideOrientation: sideOrientation,
  18478. updatable: updatable
  18479. };
  18480. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18481. };
  18482. /**
  18483. * Creates a sphere mesh.
  18484. * Please consider using the same method from the `MeshBuilder` class instead.
  18485. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18486. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18490. */
  18491. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18492. var options = {
  18493. segments: segments,
  18494. diameterX: diameter,
  18495. diameterY: diameter,
  18496. diameterZ: diameter,
  18497. sideOrientation: sideOrientation,
  18498. updatable: updatable
  18499. };
  18500. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18501. };
  18502. /**
  18503. * Creates a cylinder or a cone mesh.
  18504. * Please consider using the same method from the `MeshBuilder` class instead.
  18505. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18506. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18507. * 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.
  18508. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18509. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18511. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18513. */
  18514. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18515. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18516. if (scene !== undefined) {
  18517. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18518. updatable = scene;
  18519. }
  18520. scene = subdivisions;
  18521. subdivisions = 1;
  18522. }
  18523. var options = {
  18524. height: height,
  18525. diameterTop: diameterTop,
  18526. diameterBottom: diameterBottom,
  18527. tessellation: tessellation,
  18528. subdivisions: subdivisions,
  18529. sideOrientation: sideOrientation,
  18530. updatable: updatable
  18531. };
  18532. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18533. };
  18534. // Torus (Code from SharpDX.org)
  18535. /**
  18536. * Creates a torus mesh.
  18537. * Please consider using the same method from the `MeshBuilder` class instead.
  18538. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18539. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18540. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18544. */
  18545. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18546. var options = {
  18547. diameter: diameter,
  18548. thickness: thickness,
  18549. tessellation: tessellation,
  18550. sideOrientation: sideOrientation,
  18551. updatable: updatable
  18552. };
  18553. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18554. };
  18555. /**
  18556. * Creates a torus knot mesh.
  18557. * Please consider using the same method from the `MeshBuilder` class instead.
  18558. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18559. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18560. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18561. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18562. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18563. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18564. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18565. */
  18566. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18567. var options = {
  18568. radius: radius,
  18569. tube: tube,
  18570. radialSegments: radialSegments,
  18571. tubularSegments: tubularSegments,
  18572. p: p,
  18573. q: q,
  18574. sideOrientation: sideOrientation,
  18575. updatable: updatable
  18576. };
  18577. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18578. };
  18579. /**
  18580. * Creates a line mesh.
  18581. * Please consider using the same method from the `MeshBuilder` class instead.
  18582. * 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.
  18583. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18584. * The parameter `points` is an array successive Vector3.
  18585. * 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
  18586. * When updating an instance, remember that only point positions can change, not the number of points.
  18587. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18588. */
  18589. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18590. var options = {
  18591. points: points,
  18592. updatable: updatable,
  18593. instance: instance
  18594. };
  18595. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18596. };
  18597. /**
  18598. * Creates a dashed line mesh.
  18599. * Please consider using the same method from the `MeshBuilder` class instead.
  18600. * 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.
  18601. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18602. * The parameter `points` is an array successive Vector3.
  18603. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18604. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18605. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18606. * 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
  18607. * When updating an instance, remember that only point positions can change, not the number of points.
  18608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18609. */
  18610. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18611. var options = {
  18612. points: points,
  18613. dashSize: dashSize,
  18614. gapSize: gapSize,
  18615. dashNb: dashNb,
  18616. updatable: updatable
  18617. };
  18618. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18619. };
  18620. /**
  18621. * Creates an extruded shape mesh.
  18622. * 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.
  18623. * Please consider using the same method from the `MeshBuilder` class instead.
  18624. *
  18625. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18626. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  18627. * extruded along the Z axis.
  18628. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18629. * The parameter `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.
  18630. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18631. * 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
  18632. * 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
  18633. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18637. */
  18638. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18639. var options = {
  18640. shape: shape,
  18641. path: path,
  18642. scale: scale,
  18643. rotation: rotation,
  18644. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18645. sideOrientation: sideOrientation,
  18646. instance: instance,
  18647. updatable: updatable
  18648. };
  18649. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18650. };
  18651. /**
  18652. * Creates an custom extruded shape mesh.
  18653. * 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.
  18654. * Please consider using the same method from the `MeshBuilder` class instead.
  18655. *
  18656. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18657. * 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
  18658. * extruded along the Z axis.
  18659. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18660. * 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
  18661. * and the distance of this point from the begining of the path :
  18662. * ```rotationFunction = function(i, distance) {
  18663. * // do things
  18664. * return rotationValue; }```
  18665. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18666. * 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
  18667. * and the distance of this point from the begining of the path :
  18668. * ````scaleFunction = function(i, distance) {
  18669. * // do things
  18670. * return scaleValue;}```
  18671. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18672. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18673. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18674. * 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
  18675. * 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
  18676. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18677. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18678. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18679. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18680. */
  18681. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18682. var options = {
  18683. shape: shape,
  18684. path: path,
  18685. scaleFunction: scaleFunction,
  18686. rotationFunction: rotationFunction,
  18687. ribbonCloseArray: ribbonCloseArray,
  18688. ribbonClosePath: ribbonClosePath,
  18689. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18690. sideOrientation: sideOrientation,
  18691. instance: instance,
  18692. updatable: updatable
  18693. };
  18694. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18695. };
  18696. /**
  18697. * Creates lathe mesh.
  18698. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18699. * Please consider using the same method from the `MeshBuilder` class instead.
  18700. *
  18701. * 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
  18702. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18703. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18704. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  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.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18710. var options = {
  18711. shape: shape,
  18712. radius: radius,
  18713. tessellation: tessellation,
  18714. sideOrientation: sideOrientation,
  18715. updatable: updatable
  18716. };
  18717. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18718. };
  18719. /**
  18720. * Creates a plane mesh.
  18721. * Please consider using the same method from the `MeshBuilder` class instead.
  18722. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18723. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18724. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18726. */
  18727. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18728. var options = {
  18729. size: size,
  18730. width: size,
  18731. height: size,
  18732. sideOrientation: sideOrientation,
  18733. updatable: updatable
  18734. };
  18735. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18736. };
  18737. /**
  18738. * Creates a ground mesh.
  18739. * Please consider using the same method from the `MeshBuilder` class instead.
  18740. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18741. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18742. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18743. */
  18744. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18745. var options = {
  18746. width: width,
  18747. height: height,
  18748. subdivisions: subdivisions,
  18749. updatable: updatable
  18750. };
  18751. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18752. };
  18753. /**
  18754. * Creates a tiled ground mesh.
  18755. * Please consider using the same method from the `MeshBuilder` class instead.
  18756. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18757. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18758. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18759. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18760. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18761. * numbers of subdivisions on the ground width and height of each tile.
  18762. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18763. */
  18764. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18765. var options = {
  18766. xmin: xmin,
  18767. zmin: zmin,
  18768. xmax: xmax,
  18769. zmax: zmax,
  18770. subdivisions: subdivisions,
  18771. precision: precision,
  18772. updatable: updatable
  18773. };
  18774. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18775. };
  18776. /**
  18777. * Creates a ground mesh from a height map.
  18778. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18779. * Please consider using the same method from the `MeshBuilder` class instead.
  18780. * The parameter `url` sets the URL of the height map image resource.
  18781. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18782. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18783. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18784. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18785. * 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).
  18786. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18787. * return; }```
  18788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18789. */
  18790. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18791. var options = {
  18792. width: width,
  18793. height: height,
  18794. subdivisions: subdivisions,
  18795. minHeight: minHeight,
  18796. maxHeight: maxHeight,
  18797. updatable: updatable,
  18798. onReady: onReady
  18799. };
  18800. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18801. };
  18802. /**
  18803. * Creates a tube mesh.
  18804. * 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.
  18805. *
  18806. * Please consider using the same method from the `MeshBuilder` class instead.
  18807. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18808. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18809. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18810. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18811. * 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.
  18812. * It must return a radius value (positive float) :
  18813. * ```var radiusFunction = function(i, distance) {
  18814. * // do things
  18815. * return radius; }```
  18816. * 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
  18817. * 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
  18818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18821. */
  18822. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18823. var options = {
  18824. path: path,
  18825. radius: radius,
  18826. tessellation: tessellation,
  18827. radiusFunction: radiusFunction,
  18828. arc: 1,
  18829. cap: cap,
  18830. updatable: updatable,
  18831. sideOrientation: sideOrientation,
  18832. instance: instance
  18833. };
  18834. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18835. };
  18836. /**
  18837. * Creates a polyhedron mesh.
  18838. *
  18839. * Please consider using the same method from the `MeshBuilder` class instead.
  18840. * 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
  18841. * to choose the wanted type.
  18842. * The parameter `size` (positive float, default 1) sets the polygon size.
  18843. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18844. * 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`.
  18845. * 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
  18846. * 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)`).
  18847. * 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
  18848. * 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.
  18849. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18850. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18852. */
  18853. Mesh.CreatePolyhedron = function (name, options, scene) {
  18854. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18855. };
  18856. /**
  18857. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18858. * Please consider using the same method from the `MeshBuilder` class instead.
  18859. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18860. * 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`).
  18861. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18862. * 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.
  18863. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18864. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18866. */
  18867. Mesh.CreateIcoSphere = function (name, options, scene) {
  18868. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18869. };
  18870. /**
  18871. * Creates a decal mesh.
  18872. * Please consider using the same method from the `MeshBuilder` class instead.
  18873. * 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.
  18874. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18875. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18876. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18877. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18878. */
  18879. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18880. var options = {
  18881. position: position,
  18882. normal: normal,
  18883. size: size,
  18884. angle: angle
  18885. };
  18886. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18887. };
  18888. // Skeletons
  18889. /**
  18890. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18891. */
  18892. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18893. var source;
  18894. if (!this._sourcePositions) {
  18895. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18896. this._sourcePositions = new Float32Array(source);
  18897. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18898. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18899. }
  18900. }
  18901. return this._sourcePositions;
  18902. };
  18903. /**
  18904. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18905. */
  18906. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18907. var source;
  18908. if (!this._sourceNormals) {
  18909. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18910. this._sourceNormals = new Float32Array(source);
  18911. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18912. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18913. }
  18914. }
  18915. return this._sourceNormals;
  18916. };
  18917. /**
  18918. * Update the vertex buffers by applying transformation from the bones
  18919. * @param {skeleton} skeleton to apply
  18920. */
  18921. Mesh.prototype.applySkeleton = function (skeleton) {
  18922. if (!this.geometry) {
  18923. return;
  18924. }
  18925. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18926. return;
  18927. }
  18928. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18929. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18930. return this;
  18931. }
  18932. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18933. return this;
  18934. }
  18935. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18936. return this;
  18937. }
  18938. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18939. return this;
  18940. }
  18941. if (!this._sourcePositions) {
  18942. this.setPositionsForCPUSkinning();
  18943. }
  18944. if (!this._sourceNormals) {
  18945. this.setNormalsForCPUSkinning();
  18946. }
  18947. // positionsData checks for not being Float32Array will only pass at most once
  18948. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18949. if (!(positionsData instanceof Float32Array)) {
  18950. positionsData = new Float32Array(positionsData);
  18951. }
  18952. // normalsData checks for not being Float32Array will only pass at most once
  18953. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18954. if (!(normalsData instanceof Float32Array)) {
  18955. normalsData = new Float32Array(normalsData);
  18956. }
  18957. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18958. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18959. var needExtras = this.numBoneInfluencers > 4;
  18960. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18961. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18962. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18963. var tempVector3 = BABYLON.Vector3.Zero();
  18964. var finalMatrix = new BABYLON.Matrix();
  18965. var tempMatrix = new BABYLON.Matrix();
  18966. var matWeightIdx = 0;
  18967. var inf;
  18968. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18969. var weight;
  18970. for (inf = 0; inf < 4; inf++) {
  18971. weight = matricesWeightsData[matWeightIdx + inf];
  18972. if (weight > 0) {
  18973. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18974. finalMatrix.addToSelf(tempMatrix);
  18975. }
  18976. else
  18977. break;
  18978. }
  18979. if (needExtras) {
  18980. for (inf = 0; inf < 4; inf++) {
  18981. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18982. if (weight > 0) {
  18983. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18984. finalMatrix.addToSelf(tempMatrix);
  18985. }
  18986. else
  18987. break;
  18988. }
  18989. }
  18990. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18991. tempVector3.toArray(positionsData, index);
  18992. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18993. tempVector3.toArray(normalsData, index);
  18994. finalMatrix.reset();
  18995. }
  18996. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18997. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18998. return this;
  18999. };
  19000. // Tools
  19001. /**
  19002. * Returns an object `{min: Vector3, max: Vector3}`
  19003. * This min and max `Vector3` are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  19004. */
  19005. Mesh.MinMax = function (meshes) {
  19006. var minVector = null;
  19007. var maxVector = null;
  19008. for (var i in meshes) {
  19009. var mesh = meshes[i];
  19010. var boundingBox = mesh.getBoundingInfo().boundingBox;
  19011. if (!minVector) {
  19012. minVector = boundingBox.minimumWorld;
  19013. maxVector = boundingBox.maximumWorld;
  19014. continue;
  19015. }
  19016. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  19017. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  19018. }
  19019. return {
  19020. min: minVector,
  19021. max: maxVector
  19022. };
  19023. };
  19024. /**
  19025. * Returns a `Vector3`, the center of the `{min: Vector3, max: Vector3}` or the center of MinMax vector3 computed from a mesh array.
  19026. */
  19027. Mesh.Center = function (meshesOrMinMaxVector) {
  19028. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  19029. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  19030. };
  19031. /**
  19032. * Merge the array of meshes into a single mesh for performance reasons.
  19033. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  19034. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  19035. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  19036. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  19037. */
  19038. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  19039. if (disposeSource === void 0) { disposeSource = true; }
  19040. var index;
  19041. if (!allow32BitsIndices) {
  19042. var totalVertices = 0;
  19043. // Counting vertices
  19044. for (index = 0; index < meshes.length; index++) {
  19045. if (meshes[index]) {
  19046. totalVertices += meshes[index].getTotalVertices();
  19047. if (totalVertices > 65536) {
  19048. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  19049. return null;
  19050. }
  19051. }
  19052. }
  19053. }
  19054. // Merge
  19055. var vertexData;
  19056. var otherVertexData;
  19057. var source;
  19058. for (index = 0; index < meshes.length; index++) {
  19059. if (meshes[index]) {
  19060. meshes[index].computeWorldMatrix(true);
  19061. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  19062. otherVertexData.transform(meshes[index].getWorldMatrix());
  19063. if (vertexData) {
  19064. vertexData.merge(otherVertexData);
  19065. }
  19066. else {
  19067. vertexData = otherVertexData;
  19068. source = meshes[index];
  19069. }
  19070. }
  19071. }
  19072. if (!meshSubclass) {
  19073. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  19074. }
  19075. vertexData.applyToMesh(meshSubclass);
  19076. // Setting properties
  19077. meshSubclass.material = source.material;
  19078. meshSubclass.checkCollisions = source.checkCollisions;
  19079. // Cleaning
  19080. if (disposeSource) {
  19081. for (index = 0; index < meshes.length; index++) {
  19082. if (meshes[index]) {
  19083. meshes[index].dispose();
  19084. }
  19085. }
  19086. }
  19087. return meshSubclass;
  19088. };
  19089. // Consts
  19090. Mesh._FRONTSIDE = 0;
  19091. Mesh._BACKSIDE = 1;
  19092. Mesh._DOUBLESIDE = 2;
  19093. Mesh._DEFAULTSIDE = 0;
  19094. Mesh._NO_CAP = 0;
  19095. Mesh._CAP_START = 1;
  19096. Mesh._CAP_END = 2;
  19097. Mesh._CAP_ALL = 3;
  19098. return Mesh;
  19099. })(BABYLON.AbstractMesh);
  19100. BABYLON.Mesh = Mesh;
  19101. })(BABYLON || (BABYLON = {}));
  19102. var BABYLON;
  19103. (function (BABYLON) {
  19104. var SubMesh = (function () {
  19105. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  19106. if (createBoundingBox === void 0) { createBoundingBox = true; }
  19107. this.materialIndex = materialIndex;
  19108. this.verticesStart = verticesStart;
  19109. this.verticesCount = verticesCount;
  19110. this.indexStart = indexStart;
  19111. this.indexCount = indexCount;
  19112. this._renderId = 0;
  19113. this._mesh = mesh;
  19114. this._renderingMesh = renderingMesh || mesh;
  19115. mesh.subMeshes.push(this);
  19116. this._trianglePlanes = [];
  19117. this._id = mesh.subMeshes.length - 1;
  19118. if (createBoundingBox) {
  19119. this.refreshBoundingInfo();
  19120. mesh.computeWorldMatrix(true);
  19121. }
  19122. }
  19123. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  19124. get: function () {
  19125. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  19126. },
  19127. enumerable: true,
  19128. configurable: true
  19129. });
  19130. SubMesh.prototype.getBoundingInfo = function () {
  19131. if (this.IsGlobal) {
  19132. return this._mesh.getBoundingInfo();
  19133. }
  19134. return this._boundingInfo;
  19135. };
  19136. SubMesh.prototype.getMesh = function () {
  19137. return this._mesh;
  19138. };
  19139. SubMesh.prototype.getRenderingMesh = function () {
  19140. return this._renderingMesh;
  19141. };
  19142. SubMesh.prototype.getMaterial = function () {
  19143. var rootMaterial = this._renderingMesh.material;
  19144. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  19145. var multiMaterial = rootMaterial;
  19146. return multiMaterial.getSubMaterial(this.materialIndex);
  19147. }
  19148. if (!rootMaterial) {
  19149. return this._mesh.getScene().defaultMaterial;
  19150. }
  19151. return rootMaterial;
  19152. };
  19153. // Methods
  19154. SubMesh.prototype.refreshBoundingInfo = function () {
  19155. this._lastColliderWorldVertices = null;
  19156. if (this.IsGlobal) {
  19157. return;
  19158. }
  19159. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19160. if (!data) {
  19161. this._boundingInfo = this._mesh._boundingInfo;
  19162. return;
  19163. }
  19164. var indices = this._renderingMesh.getIndices();
  19165. var extend;
  19166. //is this the only submesh?
  19167. if (this.indexStart === 0 && this.indexCount === indices.length) {
  19168. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  19169. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  19170. }
  19171. else {
  19172. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19173. }
  19174. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19175. };
  19176. SubMesh.prototype._checkCollision = function (collider) {
  19177. return this.getBoundingInfo()._checkCollision(collider);
  19178. };
  19179. SubMesh.prototype.updateBoundingInfo = function (world) {
  19180. if (!this.getBoundingInfo()) {
  19181. this.refreshBoundingInfo();
  19182. }
  19183. this.getBoundingInfo().update(world);
  19184. };
  19185. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19186. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19187. };
  19188. SubMesh.prototype.render = function (enableAlphaMode) {
  19189. this._renderingMesh.render(this, enableAlphaMode);
  19190. };
  19191. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19192. if (!this._linesIndexBuffer) {
  19193. var linesIndices = [];
  19194. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19195. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19196. }
  19197. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19198. this.linesIndexCount = linesIndices.length;
  19199. }
  19200. return this._linesIndexBuffer;
  19201. };
  19202. SubMesh.prototype.canIntersects = function (ray) {
  19203. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19204. };
  19205. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19206. var intersectInfo = null;
  19207. // LineMesh first as it's also a Mesh...
  19208. if (this._mesh instanceof BABYLON.LinesMesh) {
  19209. var lineMesh = this._mesh;
  19210. // Line test
  19211. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19212. var p0 = positions[indices[index]];
  19213. var p1 = positions[indices[index + 1]];
  19214. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19215. if (length < 0) {
  19216. continue;
  19217. }
  19218. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19219. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19220. if (fastCheck) {
  19221. break;
  19222. }
  19223. }
  19224. }
  19225. }
  19226. else {
  19227. // Triangles test
  19228. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19229. var p0 = positions[indices[index]];
  19230. var p1 = positions[indices[index + 1]];
  19231. var p2 = positions[indices[index + 2]];
  19232. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19233. if (currentIntersectInfo) {
  19234. if (currentIntersectInfo.distance < 0) {
  19235. continue;
  19236. }
  19237. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19238. intersectInfo = currentIntersectInfo;
  19239. intersectInfo.faceId = index / 3;
  19240. if (fastCheck) {
  19241. break;
  19242. }
  19243. }
  19244. }
  19245. }
  19246. }
  19247. return intersectInfo;
  19248. };
  19249. // Clone
  19250. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19251. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19252. if (!this.IsGlobal) {
  19253. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19254. }
  19255. return result;
  19256. };
  19257. // Dispose
  19258. SubMesh.prototype.dispose = function () {
  19259. if (this._linesIndexBuffer) {
  19260. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19261. this._linesIndexBuffer = null;
  19262. }
  19263. // Remove from mesh
  19264. var index = this._mesh.subMeshes.indexOf(this);
  19265. this._mesh.subMeshes.splice(index, 1);
  19266. };
  19267. // Statics
  19268. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19269. var minVertexIndex = Number.MAX_VALUE;
  19270. var maxVertexIndex = -Number.MAX_VALUE;
  19271. renderingMesh = renderingMesh || mesh;
  19272. var indices = renderingMesh.getIndices();
  19273. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19274. var vertexIndex = indices[index];
  19275. if (vertexIndex < minVertexIndex)
  19276. minVertexIndex = vertexIndex;
  19277. if (vertexIndex > maxVertexIndex)
  19278. maxVertexIndex = vertexIndex;
  19279. }
  19280. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19281. };
  19282. return SubMesh;
  19283. })();
  19284. BABYLON.SubMesh = SubMesh;
  19285. })(BABYLON || (BABYLON = {}));
  19286. var BABYLON;
  19287. (function (BABYLON) {
  19288. var MeshBuilder = (function () {
  19289. function MeshBuilder() {
  19290. }
  19291. /**
  19292. * Creates a box mesh.
  19293. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19294. * The parameter `size` sets the size (float) of each box side (default 1).
  19295. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19296. * 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).
  19297. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19298. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19299. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19301. */
  19302. MeshBuilder.CreateBox = function (name, options, scene) {
  19303. var box = new BABYLON.Mesh(name, scene);
  19304. var vertexData = BABYLON.VertexData.CreateBox(options);
  19305. vertexData.applyToMesh(box, options.updatable);
  19306. return box;
  19307. };
  19308. /**
  19309. * Creates a sphere mesh.
  19310. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19311. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19312. * 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`).
  19313. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19314. * 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
  19315. * 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).
  19316. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19317. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19319. */
  19320. MeshBuilder.CreateSphere = function (name, options, scene) {
  19321. var sphere = new BABYLON.Mesh(name, scene);
  19322. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19323. vertexData.applyToMesh(sphere, options.updatable);
  19324. return sphere;
  19325. };
  19326. /**
  19327. * Creates a plane polygonal mesh. By default, this is a disc.
  19328. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19329. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19330. * 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.
  19331. * 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
  19332. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19333. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19334. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19335. */
  19336. MeshBuilder.CreateDisc = function (name, options, scene) {
  19337. var disc = new BABYLON.Mesh(name, scene);
  19338. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19339. vertexData.applyToMesh(disc, options.updatable);
  19340. return disc;
  19341. };
  19342. /**
  19343. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19344. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19345. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19346. * 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`).
  19347. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19348. * 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.
  19349. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19352. */
  19353. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19354. var sphere = new BABYLON.Mesh(name, scene);
  19355. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19356. vertexData.applyToMesh(sphere, options.updatable);
  19357. return sphere;
  19358. };
  19359. ;
  19360. /**
  19361. * Creates a ribbon mesh.
  19362. * 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.
  19363. *
  19364. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19365. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19366. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19367. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19368. * 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.
  19369. * 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.
  19370. * 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
  19371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19372. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19373. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19374. */
  19375. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19376. var pathArray = options.pathArray;
  19377. var closeArray = options.closeArray;
  19378. var closePath = options.closePath;
  19379. var offset = options.offset;
  19380. var sideOrientation = options.sideOrientation;
  19381. var instance = options.instance;
  19382. var updatable = options.updatable;
  19383. if (instance) {
  19384. // positionFunction : ribbon case
  19385. // only pathArray and sideOrientation parameters are taken into account for positions update
  19386. var positionFunction = function (positions) {
  19387. var minlg = pathArray[0].length;
  19388. var i = 0;
  19389. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19390. for (var si = 1; si <= ns; si++) {
  19391. for (var p = 0; p < pathArray.length; p++) {
  19392. var path = pathArray[p];
  19393. var l = path.length;
  19394. minlg = (minlg < l) ? minlg : l;
  19395. var j = 0;
  19396. while (j < minlg) {
  19397. positions[i] = path[j].x;
  19398. positions[i + 1] = path[j].y;
  19399. positions[i + 2] = path[j].z;
  19400. j++;
  19401. i += 3;
  19402. }
  19403. if (instance._closePath) {
  19404. positions[i] = path[0].x;
  19405. positions[i + 1] = path[0].y;
  19406. positions[i + 2] = path[0].z;
  19407. i += 3;
  19408. }
  19409. }
  19410. }
  19411. };
  19412. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19413. positionFunction(positions);
  19414. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19415. if (!(instance.areNormalsFrozen)) {
  19416. var indices = instance.getIndices();
  19417. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19418. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19419. if (instance._closePath) {
  19420. var indexFirst = 0;
  19421. var indexLast = 0;
  19422. for (var p = 0; p < pathArray.length; p++) {
  19423. indexFirst = instance._idx[p] * 3;
  19424. if (p + 1 < pathArray.length) {
  19425. indexLast = (instance._idx[p + 1] - 1) * 3;
  19426. }
  19427. else {
  19428. indexLast = normals.length - 3;
  19429. }
  19430. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19431. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19432. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19433. normals[indexLast] = normals[indexFirst];
  19434. normals[indexLast + 1] = normals[indexFirst + 1];
  19435. normals[indexLast + 2] = normals[indexFirst + 2];
  19436. }
  19437. }
  19438. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19439. }
  19440. return instance;
  19441. }
  19442. else {
  19443. var ribbon = new BABYLON.Mesh(name, scene);
  19444. ribbon.sideOrientation = sideOrientation;
  19445. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19446. if (closePath) {
  19447. ribbon._idx = vertexData._idx;
  19448. }
  19449. ribbon._closePath = closePath;
  19450. ribbon._closeArray = closeArray;
  19451. vertexData.applyToMesh(ribbon, updatable);
  19452. return ribbon;
  19453. }
  19454. };
  19455. /**
  19456. * Creates a cylinder or a cone mesh.
  19457. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19458. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19459. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19460. * 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.
  19461. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19462. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19463. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19464. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19465. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19466. * 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).
  19467. * 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
  19468. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19469. * 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
  19470. * 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.
  19471. * If `enclose` is false, a ring surface is one element.
  19472. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19473. * 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
  19474. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19475. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19477. */
  19478. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19479. var cylinder = new BABYLON.Mesh(name, scene);
  19480. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19481. vertexData.applyToMesh(cylinder, options.updatable);
  19482. return cylinder;
  19483. };
  19484. /**
  19485. * Creates a torus mesh.
  19486. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19487. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19488. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19489. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19490. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19493. */
  19494. MeshBuilder.CreateTorus = function (name, options, scene) {
  19495. var torus = new BABYLON.Mesh(name, scene);
  19496. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19497. vertexData.applyToMesh(torus, options.updatable);
  19498. return torus;
  19499. };
  19500. /**
  19501. * Creates a torus knot mesh.
  19502. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19503. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19504. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19505. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19506. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19507. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19508. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19509. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19510. */
  19511. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19512. var torusKnot = new BABYLON.Mesh(name, scene);
  19513. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19514. vertexData.applyToMesh(torusKnot, options.updatable);
  19515. return torusKnot;
  19516. };
  19517. /**
  19518. * Creates a line system mesh.
  19519. * A line system is a pool of many lines gathered in a single mesh.
  19520. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19521. * 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.
  19522. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19523. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19524. * 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
  19525. * 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
  19526. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19527. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19528. */
  19529. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19530. var instance = options.instance;
  19531. var lines = options.lines;
  19532. if (instance) {
  19533. var positionFunction = function (positions) {
  19534. var i = 0;
  19535. for (var l = 0; l < lines.length; l++) {
  19536. var points = lines[l];
  19537. for (var p = 0; p < points.length; p++) {
  19538. positions[i] = points[p].x;
  19539. positions[i + 1] = points[p].y;
  19540. positions[i + 2] = points[p].z;
  19541. i += 3;
  19542. }
  19543. }
  19544. };
  19545. instance.updateMeshPositions(positionFunction, false);
  19546. return instance;
  19547. }
  19548. // line system creation
  19549. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19550. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19551. vertexData.applyToMesh(lineSystem, options.updatable);
  19552. return lineSystem;
  19553. };
  19554. /**
  19555. * Creates a line mesh.
  19556. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19557. * 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.
  19558. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19559. * The parameter `points` is an array successive Vector3.
  19560. * 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
  19561. * When updating an instance, remember that only point positions can change, not the number of points.
  19562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19563. */
  19564. MeshBuilder.CreateLines = function (name, options, scene) {
  19565. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19566. return lines;
  19567. };
  19568. /**
  19569. * Creates a dashed line mesh.
  19570. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19571. * 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.
  19572. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19573. * The parameter `points` is an array successive Vector3.
  19574. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19575. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19576. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19577. * 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
  19578. * When updating an instance, remember that only point positions can change, not the number of points.
  19579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19580. */
  19581. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19582. var points = options.points;
  19583. var instance = options.instance;
  19584. var gapSize = options.gapSize;
  19585. var dashNb = options.dashNb;
  19586. var dashSize = options.dashSize;
  19587. if (instance) {
  19588. var positionFunction = function (positions) {
  19589. var curvect = BABYLON.Vector3.Zero();
  19590. var nbSeg = positions.length / 6;
  19591. var lg = 0;
  19592. var nb = 0;
  19593. var shft = 0;
  19594. var dashshft = 0;
  19595. var curshft = 0;
  19596. var p = 0;
  19597. var i = 0;
  19598. var j = 0;
  19599. for (i = 0; i < points.length - 1; i++) {
  19600. points[i + 1].subtractToRef(points[i], curvect);
  19601. lg += curvect.length();
  19602. }
  19603. shft = lg / nbSeg;
  19604. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19605. for (i = 0; i < points.length - 1; i++) {
  19606. points[i + 1].subtractToRef(points[i], curvect);
  19607. nb = Math.floor(curvect.length() / shft);
  19608. curvect.normalize();
  19609. j = 0;
  19610. while (j < nb && p < positions.length) {
  19611. curshft = shft * j;
  19612. positions[p] = points[i].x + curshft * curvect.x;
  19613. positions[p + 1] = points[i].y + curshft * curvect.y;
  19614. positions[p + 2] = points[i].z + curshft * curvect.z;
  19615. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19616. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19617. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19618. p += 6;
  19619. j++;
  19620. }
  19621. }
  19622. while (p < positions.length) {
  19623. positions[p] = points[i].x;
  19624. positions[p + 1] = points[i].y;
  19625. positions[p + 2] = points[i].z;
  19626. p += 3;
  19627. }
  19628. };
  19629. instance.updateMeshPositions(positionFunction, false);
  19630. return instance;
  19631. }
  19632. // dashed lines creation
  19633. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19634. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19635. vertexData.applyToMesh(dashedLines, options.updatable);
  19636. dashedLines.dashSize = dashSize;
  19637. dashedLines.gapSize = gapSize;
  19638. return dashedLines;
  19639. };
  19640. /**
  19641. * Creates an extruded shape mesh.
  19642. * 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.
  19643. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19644. *
  19645. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19646. * 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
  19647. * extruded along the Z axis.
  19648. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19649. * 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.
  19650. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19651. * 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
  19652. * 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
  19653. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19654. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19655. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19657. */
  19658. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19659. var path = options.path;
  19660. var shape = options.shape;
  19661. var scale = options.scale || 1;
  19662. var rotation = options.rotation || 0;
  19663. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19664. var updatable = options.updatable;
  19665. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19666. var instance = options.instance;
  19667. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19668. };
  19669. /**
  19670. * Creates an custom extruded shape mesh.
  19671. * 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.
  19672. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19673. *
  19674. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19675. * 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
  19676. * extruded along the Z axis.
  19677. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19678. * 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
  19679. * and the distance of this point from the begining of the path :
  19680. * ```rotationFunction = function(i, distance) {
  19681. * // do things
  19682. * return rotationValue; }```
  19683. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19684. * 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
  19685. * and the distance of this point from the begining of the path :
  19686. * ````scaleFunction = function(i, distance) {
  19687. * // do things
  19688. * return scaleValue;}```
  19689. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19690. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19691. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19692. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  19693. * 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
  19694. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19695. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19696. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19697. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19698. */
  19699. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19700. var path = options.path;
  19701. var shape = options.shape;
  19702. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19703. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19704. var ribbonCloseArray = options.ribbonCloseArray || false;
  19705. var ribbonClosePath = options.ribbonClosePath || false;
  19706. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19707. var updatable = options.updatable;
  19708. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19709. var instance = options.instance;
  19710. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19711. };
  19712. /**
  19713. * Creates lathe mesh.
  19714. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19715. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19716. *
  19717. * 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
  19718. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19719. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19720. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19721. * 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.
  19722. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19723. * 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
  19724. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19725. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19726. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19727. */
  19728. MeshBuilder.CreateLathe = function (name, options, scene) {
  19729. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19730. var closed = (options.closed === undefined) ? true : options.closed;
  19731. var shape = options.shape;
  19732. var radius = options.radius || 1;
  19733. var tessellation = options.tessellation || 64;
  19734. var updatable = options.updatable;
  19735. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19736. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19737. var pi2 = Math.PI * 2;
  19738. var paths = new Array();
  19739. var i = 0;
  19740. var p = 0;
  19741. var step = pi2 / tessellation * arc;
  19742. var rotated;
  19743. var path = new Array();
  19744. ;
  19745. for (i = 0; i <= tessellation; i++) {
  19746. var path = [];
  19747. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19748. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19749. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19750. }
  19751. for (p = 0; p < shape.length; p++) {
  19752. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19753. path.push(rotated);
  19754. }
  19755. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19756. 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));
  19757. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19758. }
  19759. paths.push(path);
  19760. }
  19761. // lathe ribbon
  19762. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19763. return lathe;
  19764. };
  19765. /**
  19766. * Creates a plane mesh.
  19767. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19768. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19769. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19770. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19771. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19772. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19774. */
  19775. MeshBuilder.CreatePlane = function (name, options, scene) {
  19776. var plane = new BABYLON.Mesh(name, scene);
  19777. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19778. vertexData.applyToMesh(plane, options.updatable);
  19779. if (options.sourcePlane) {
  19780. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19781. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19782. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19783. plane.rotate(vectorProduct, product);
  19784. }
  19785. return plane;
  19786. };
  19787. /**
  19788. * Creates a ground mesh.
  19789. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19790. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19791. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19792. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19793. */
  19794. MeshBuilder.CreateGround = function (name, options, scene) {
  19795. var ground = new BABYLON.GroundMesh(name, scene);
  19796. ground._setReady(false);
  19797. ground._subdivisions = options.subdivisions || 1;
  19798. ground._width = options.width || 1;
  19799. ground._height = options.height || 1;
  19800. ground._maxX = ground._width / 2;
  19801. ground._maxZ = ground._height / 2;
  19802. ground._minX = -ground._maxX;
  19803. ground._minZ = -ground._maxZ;
  19804. var vertexData = BABYLON.VertexData.CreateGround(options);
  19805. vertexData.applyToMesh(ground, options.updatable);
  19806. ground._setReady(true);
  19807. return ground;
  19808. };
  19809. /**
  19810. * Creates a tiled ground mesh.
  19811. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19812. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19813. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19814. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19815. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19816. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19817. * numbers of subdivisions on the ground width and height of each tile.
  19818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19819. */
  19820. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19821. var tiledGround = new BABYLON.Mesh(name, scene);
  19822. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19823. vertexData.applyToMesh(tiledGround, options.updatable);
  19824. return tiledGround;
  19825. };
  19826. /**
  19827. * Creates a ground mesh from a height map.
  19828. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19829. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19830. * The parameter `url` sets the URL of the height map image resource.
  19831. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19832. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19833. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19834. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19835. * 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).
  19836. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19837. * return; }```
  19838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19839. */
  19840. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19841. var width = options.width || 10;
  19842. var height = options.height || 10;
  19843. var subdivisions = options.subdivisions || 1;
  19844. var minHeight = options.minHeight;
  19845. var maxHeight = options.maxHeight || 10;
  19846. var updatable = options.updatable;
  19847. var onReady = options.onReady;
  19848. var ground = new BABYLON.GroundMesh(name, scene);
  19849. ground._subdivisions = subdivisions;
  19850. ground._width = width;
  19851. ground._height = height;
  19852. ground._maxX = ground._width / 2;
  19853. ground._maxZ = ground._height / 2;
  19854. ground._minX = -ground._maxX;
  19855. ground._minZ = -ground._maxZ;
  19856. ground._setReady(false);
  19857. var onload = function (img) {
  19858. // Getting height map data
  19859. var canvas = document.createElement("canvas");
  19860. var context = canvas.getContext("2d");
  19861. var bufferWidth = img.width;
  19862. var bufferHeight = img.height;
  19863. canvas.width = bufferWidth;
  19864. canvas.height = bufferHeight;
  19865. context.drawImage(img, 0, 0);
  19866. // Create VertexData from map data
  19867. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19868. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19869. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19870. width: width, height: height,
  19871. subdivisions: subdivisions,
  19872. minHeight: minHeight, maxHeight: maxHeight,
  19873. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19874. });
  19875. vertexData.applyToMesh(ground, updatable);
  19876. ground._setReady(true);
  19877. //execute ready callback, if set
  19878. if (onReady) {
  19879. onReady(ground);
  19880. }
  19881. };
  19882. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19883. return ground;
  19884. };
  19885. /**
  19886. * Creates a tube mesh.
  19887. * 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.
  19888. *
  19889. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19890. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19891. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19892. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19893. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19894. * 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.
  19895. * It must return a radius value (positive float) :
  19896. * ```var radiusFunction = function(i, distance) {
  19897. * // do things
  19898. * return radius; }```
  19899. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19900. * 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
  19901. * 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
  19902. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19903. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19905. */
  19906. MeshBuilder.CreateTube = function (name, options, scene) {
  19907. var path = options.path;
  19908. var radius = options.radius || 1;
  19909. var tessellation = options.tessellation || 64;
  19910. var radiusFunction = options.radiusFunction;
  19911. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19912. var updatable = options.updatable;
  19913. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19914. var instance = options.instance;
  19915. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19916. // tube geometry
  19917. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19918. var tangents = path3D.getTangents();
  19919. var normals = path3D.getNormals();
  19920. var distances = path3D.getDistances();
  19921. var pi2 = Math.PI * 2;
  19922. var step = pi2 / tessellation * arc;
  19923. var returnRadius = function () { return radius; };
  19924. var radiusFunctionFinal = radiusFunction || returnRadius;
  19925. var circlePath;
  19926. var rad;
  19927. var normal;
  19928. var rotated;
  19929. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19930. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19931. for (var i = 0; i < path.length; i++) {
  19932. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19933. circlePath = Array(); // current circle array
  19934. normal = normals[i]; // current normal
  19935. for (var t = 0; t < tessellation; t++) {
  19936. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19937. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19938. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19939. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19940. circlePath[t] = rotated;
  19941. }
  19942. circlePaths[index] = circlePath;
  19943. index++;
  19944. }
  19945. // cap
  19946. var capPath = function (nbPoints, pathIndex) {
  19947. var pointCap = Array();
  19948. for (var i = 0; i < nbPoints; i++) {
  19949. pointCap.push(path[pathIndex]);
  19950. }
  19951. return pointCap;
  19952. };
  19953. switch (cap) {
  19954. case BABYLON.Mesh.NO_CAP:
  19955. break;
  19956. case BABYLON.Mesh.CAP_START:
  19957. circlePaths[0] = capPath(tessellation, 0);
  19958. circlePaths[1] = circlePaths[2].slice(0);
  19959. break;
  19960. case BABYLON.Mesh.CAP_END:
  19961. circlePaths[index] = circlePaths[index - 1].slice(0);
  19962. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19963. break;
  19964. case BABYLON.Mesh.CAP_ALL:
  19965. circlePaths[0] = capPath(tessellation, 0);
  19966. circlePaths[1] = circlePaths[2].slice(0);
  19967. circlePaths[index] = circlePaths[index - 1].slice(0);
  19968. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19969. break;
  19970. default:
  19971. break;
  19972. }
  19973. return circlePaths;
  19974. };
  19975. var path3D;
  19976. var pathArray;
  19977. if (instance) {
  19978. var arc = options.arc || instance.arc;
  19979. path3D = (instance.path3D).update(path);
  19980. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19981. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19982. instance.path3D = path3D;
  19983. instance.pathArray = pathArray;
  19984. instance.arc = arc;
  19985. return instance;
  19986. }
  19987. // tube creation
  19988. path3D = new BABYLON.Path3D(path);
  19989. var newPathArray = new Array();
  19990. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19991. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19992. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19993. tube.pathArray = pathArray;
  19994. tube.path3D = path3D;
  19995. tube.tessellation = tessellation;
  19996. tube.cap = cap;
  19997. tube.arc = options.arc;
  19998. return tube;
  19999. };
  20000. /**
  20001. * Creates a polyhedron mesh.
  20002. *
  20003. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  20004. * 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
  20005. * to choose the wanted type.
  20006. * The parameter `size` (positive float, default 1) sets the polygon size.
  20007. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20008. * 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`.
  20009. * 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
  20010. * 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)`).
  20011. * 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
  20012. * 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.
  20013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20016. */
  20017. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  20018. var polyhedron = new BABYLON.Mesh(name, scene);
  20019. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  20020. vertexData.applyToMesh(polyhedron, options.updatable);
  20021. return polyhedron;
  20022. };
  20023. /**
  20024. * Creates a decal mesh.
  20025. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  20026. * 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.
  20027. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20028. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20029. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  20030. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20031. */
  20032. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  20033. var indices = sourceMesh.getIndices();
  20034. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20035. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20036. var position = options.position || BABYLON.Vector3.Zero();
  20037. var normal = options.normal || BABYLON.Vector3.Up();
  20038. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  20039. var angle = options.angle || 0;
  20040. // Getting correct rotation
  20041. if (!normal) {
  20042. var target = new BABYLON.Vector3(0, 0, 1);
  20043. var camera = sourceMesh.getScene().activeCamera;
  20044. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  20045. normal = camera.globalPosition.subtract(cameraWorldTarget);
  20046. }
  20047. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  20048. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  20049. var pitch = Math.atan2(normal.y, len);
  20050. // Matrix
  20051. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  20052. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  20053. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  20054. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  20055. var vertexData = new BABYLON.VertexData();
  20056. vertexData.indices = [];
  20057. vertexData.positions = [];
  20058. vertexData.normals = [];
  20059. vertexData.uvs = [];
  20060. var currentVertexDataIndex = 0;
  20061. var extractDecalVector3 = function (indexId) {
  20062. var vertexId = indices[indexId];
  20063. var result = new BABYLON.PositionNormalVertex();
  20064. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  20065. // Send vector to decal local world
  20066. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  20067. // Get normal
  20068. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  20069. return result;
  20070. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  20071. var clip = function (vertices, axis) {
  20072. if (vertices.length === 0) {
  20073. return vertices;
  20074. }
  20075. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  20076. var clipVertices = function (v0, v1) {
  20077. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  20078. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  20079. };
  20080. var result = new Array();
  20081. for (var index = 0; index < vertices.length; index += 3) {
  20082. var v1Out;
  20083. var v2Out;
  20084. var v3Out;
  20085. var total = 0;
  20086. var nV1, nV2, nV3, nV4;
  20087. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  20088. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  20089. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  20090. v1Out = d1 > 0;
  20091. v2Out = d2 > 0;
  20092. v3Out = d3 > 0;
  20093. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  20094. switch (total) {
  20095. case 0:
  20096. result.push(vertices[index]);
  20097. result.push(vertices[index + 1]);
  20098. result.push(vertices[index + 2]);
  20099. break;
  20100. case 1:
  20101. if (v1Out) {
  20102. nV1 = vertices[index + 1];
  20103. nV2 = vertices[index + 2];
  20104. nV3 = clipVertices(vertices[index], nV1);
  20105. nV4 = clipVertices(vertices[index], nV2);
  20106. }
  20107. if (v2Out) {
  20108. nV1 = vertices[index];
  20109. nV2 = vertices[index + 2];
  20110. nV3 = clipVertices(vertices[index + 1], nV1);
  20111. nV4 = clipVertices(vertices[index + 1], nV2);
  20112. result.push(nV3);
  20113. result.push(nV2.clone());
  20114. result.push(nV1.clone());
  20115. result.push(nV2.clone());
  20116. result.push(nV3.clone());
  20117. result.push(nV4);
  20118. break;
  20119. }
  20120. if (v3Out) {
  20121. nV1 = vertices[index];
  20122. nV2 = vertices[index + 1];
  20123. nV3 = clipVertices(vertices[index + 2], nV1);
  20124. nV4 = clipVertices(vertices[index + 2], nV2);
  20125. }
  20126. result.push(nV1.clone());
  20127. result.push(nV2.clone());
  20128. result.push(nV3);
  20129. result.push(nV4);
  20130. result.push(nV3.clone());
  20131. result.push(nV2.clone());
  20132. break;
  20133. case 2:
  20134. if (!v1Out) {
  20135. nV1 = vertices[index].clone();
  20136. nV2 = clipVertices(nV1, vertices[index + 1]);
  20137. nV3 = clipVertices(nV1, vertices[index + 2]);
  20138. result.push(nV1);
  20139. result.push(nV2);
  20140. result.push(nV3);
  20141. }
  20142. if (!v2Out) {
  20143. nV1 = vertices[index + 1].clone();
  20144. nV2 = clipVertices(nV1, vertices[index + 2]);
  20145. nV3 = clipVertices(nV1, vertices[index]);
  20146. result.push(nV1);
  20147. result.push(nV2);
  20148. result.push(nV3);
  20149. }
  20150. if (!v3Out) {
  20151. nV1 = vertices[index + 2].clone();
  20152. nV2 = clipVertices(nV1, vertices[index]);
  20153. nV3 = clipVertices(nV1, vertices[index + 1]);
  20154. result.push(nV1);
  20155. result.push(nV2);
  20156. result.push(nV3);
  20157. }
  20158. break;
  20159. case 3:
  20160. break;
  20161. }
  20162. }
  20163. return result;
  20164. };
  20165. for (var index = 0; index < indices.length; index += 3) {
  20166. var faceVertices = new Array();
  20167. faceVertices.push(extractDecalVector3(index));
  20168. faceVertices.push(extractDecalVector3(index + 1));
  20169. faceVertices.push(extractDecalVector3(index + 2));
  20170. // Clip
  20171. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20172. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20173. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20174. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20175. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20176. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20177. if (faceVertices.length === 0) {
  20178. continue;
  20179. }
  20180. // Add UVs and get back to world
  20181. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20182. var vertex = faceVertices[vIndex];
  20183. //TODO check for Int32Array
  20184. vertexData.indices.push(currentVertexDataIndex);
  20185. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20186. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20187. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20188. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20189. currentVertexDataIndex++;
  20190. }
  20191. }
  20192. // Return mesh
  20193. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20194. vertexData.applyToMesh(decal);
  20195. decal.position = position.clone();
  20196. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20197. return decal;
  20198. };
  20199. // Privates
  20200. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20201. // extrusion geometry
  20202. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20203. var tangents = path3D.getTangents();
  20204. var normals = path3D.getNormals();
  20205. var binormals = path3D.getBinormals();
  20206. var distances = path3D.getDistances();
  20207. var angle = 0;
  20208. var returnScale = function () { return scale; };
  20209. var returnRotation = function () { return rotation; };
  20210. var rotate = custom ? rotateFunction : returnRotation;
  20211. var scl = custom ? scaleFunction : returnScale;
  20212. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20213. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20214. for (var i = 0; i < curve.length; i++) {
  20215. var shapePath = new Array();
  20216. var angleStep = rotate(i, distances[i]);
  20217. var scaleRatio = scl(i, distances[i]);
  20218. for (var p = 0; p < shape.length; p++) {
  20219. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20220. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20221. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20222. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20223. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20224. shapePath[p] = rotated;
  20225. }
  20226. shapePaths[index] = shapePath;
  20227. angle += angleStep;
  20228. index++;
  20229. }
  20230. // cap
  20231. var capPath = function (shapePath) {
  20232. var pointCap = Array();
  20233. var barycenter = BABYLON.Vector3.Zero();
  20234. var i;
  20235. for (i = 0; i < shapePath.length; i++) {
  20236. barycenter.addInPlace(shapePath[i]);
  20237. }
  20238. barycenter.scaleInPlace(1 / shapePath.length);
  20239. for (i = 0; i < shapePath.length; i++) {
  20240. pointCap.push(barycenter);
  20241. }
  20242. return pointCap;
  20243. };
  20244. switch (cap) {
  20245. case BABYLON.Mesh.NO_CAP:
  20246. break;
  20247. case BABYLON.Mesh.CAP_START:
  20248. shapePaths[0] = capPath(shapePaths[2]);
  20249. shapePaths[1] = shapePaths[2].slice(0);
  20250. break;
  20251. case BABYLON.Mesh.CAP_END:
  20252. shapePaths[index] = shapePaths[index - 1];
  20253. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20254. break;
  20255. case BABYLON.Mesh.CAP_ALL:
  20256. shapePaths[0] = capPath(shapePaths[2]);
  20257. shapePaths[1] = shapePaths[2].slice(0);
  20258. shapePaths[index] = shapePaths[index - 1];
  20259. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20260. break;
  20261. default:
  20262. break;
  20263. }
  20264. return shapePaths;
  20265. };
  20266. var path3D;
  20267. var pathArray;
  20268. if (instance) {
  20269. path3D = (instance.path3D).update(curve);
  20270. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20271. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20272. return instance;
  20273. }
  20274. // extruded shape creation
  20275. path3D = new BABYLON.Path3D(curve);
  20276. var newShapePaths = new Array();
  20277. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20278. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20279. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20280. extrudedGeneric.pathArray = pathArray;
  20281. extrudedGeneric.path3D = path3D;
  20282. extrudedGeneric.cap = cap;
  20283. return extrudedGeneric;
  20284. };
  20285. return MeshBuilder;
  20286. })();
  20287. BABYLON.MeshBuilder = MeshBuilder;
  20288. })(BABYLON || (BABYLON = {}));
  20289. var BABYLON;
  20290. (function (BABYLON) {
  20291. var BaseTexture = (function () {
  20292. function BaseTexture(scene) {
  20293. this.hasAlpha = false;
  20294. this.getAlphaFromRGB = false;
  20295. this.level = 1;
  20296. this.coordinatesIndex = 0;
  20297. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20298. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20299. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20300. this.anisotropicFilteringLevel = 4;
  20301. this.isCube = false;
  20302. this.isRenderTarget = false;
  20303. this.animations = new Array();
  20304. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20305. this._scene = scene;
  20306. this._scene.textures.push(this);
  20307. }
  20308. BaseTexture.prototype.getScene = function () {
  20309. return this._scene;
  20310. };
  20311. BaseTexture.prototype.getTextureMatrix = function () {
  20312. return null;
  20313. };
  20314. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20315. return null;
  20316. };
  20317. BaseTexture.prototype.getInternalTexture = function () {
  20318. return this._texture;
  20319. };
  20320. BaseTexture.prototype.isReady = function () {
  20321. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20322. return true;
  20323. }
  20324. if (this._texture) {
  20325. return this._texture.isReady;
  20326. }
  20327. return false;
  20328. };
  20329. BaseTexture.prototype.getSize = function () {
  20330. if (this._texture._width) {
  20331. return { width: this._texture._width, height: this._texture._height };
  20332. }
  20333. if (this._texture._size) {
  20334. return { width: this._texture._size, height: this._texture._size };
  20335. }
  20336. return { width: 0, height: 0 };
  20337. };
  20338. BaseTexture.prototype.getBaseSize = function () {
  20339. if (!this.isReady() || !this._texture)
  20340. return { width: 0, height: 0 };
  20341. if (this._texture._size) {
  20342. return { width: this._texture._size, height: this._texture._size };
  20343. }
  20344. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20345. };
  20346. BaseTexture.prototype.scale = function (ratio) {
  20347. };
  20348. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20349. get: function () {
  20350. return false;
  20351. },
  20352. enumerable: true,
  20353. configurable: true
  20354. });
  20355. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20356. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20357. for (var index = 0; index < texturesCache.length; index++) {
  20358. var texturesCacheEntry = texturesCache[index];
  20359. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20360. texturesCache.splice(index, 1);
  20361. return;
  20362. }
  20363. }
  20364. };
  20365. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20366. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20367. for (var index = 0; index < texturesCache.length; index++) {
  20368. var texturesCacheEntry = texturesCache[index];
  20369. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20370. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20371. texturesCacheEntry.references++;
  20372. return texturesCacheEntry;
  20373. }
  20374. }
  20375. }
  20376. return null;
  20377. };
  20378. BaseTexture.prototype.delayLoad = function () {
  20379. };
  20380. BaseTexture.prototype.clone = function () {
  20381. return null;
  20382. };
  20383. BaseTexture.prototype.releaseInternalTexture = function () {
  20384. if (this._texture) {
  20385. this._scene.getEngine().releaseInternalTexture(this._texture);
  20386. delete this._texture;
  20387. }
  20388. };
  20389. BaseTexture.prototype.dispose = function () {
  20390. // Animations
  20391. this.getScene().stopAnimation(this);
  20392. // Remove from scene
  20393. var index = this._scene.textures.indexOf(this);
  20394. if (index >= 0) {
  20395. this._scene.textures.splice(index, 1);
  20396. }
  20397. if (this._texture === undefined) {
  20398. return;
  20399. }
  20400. // Release
  20401. this.releaseInternalTexture();
  20402. // Callback
  20403. if (this.onDispose) {
  20404. this.onDispose();
  20405. }
  20406. };
  20407. BaseTexture.prototype.serialize = function () {
  20408. if (!this.name) {
  20409. return null;
  20410. }
  20411. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20412. // Animations
  20413. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20414. return serializationObject;
  20415. };
  20416. __decorate([
  20417. BABYLON.serialize()
  20418. ], BaseTexture.prototype, "name", void 0);
  20419. __decorate([
  20420. BABYLON.serialize()
  20421. ], BaseTexture.prototype, "hasAlpha", void 0);
  20422. __decorate([
  20423. BABYLON.serialize()
  20424. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20425. __decorate([
  20426. BABYLON.serialize()
  20427. ], BaseTexture.prototype, "level", void 0);
  20428. __decorate([
  20429. BABYLON.serialize()
  20430. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20431. __decorate([
  20432. BABYLON.serialize()
  20433. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20434. __decorate([
  20435. BABYLON.serialize()
  20436. ], BaseTexture.prototype, "wrapU", void 0);
  20437. __decorate([
  20438. BABYLON.serialize()
  20439. ], BaseTexture.prototype, "wrapV", void 0);
  20440. __decorate([
  20441. BABYLON.serialize()
  20442. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20443. __decorate([
  20444. BABYLON.serialize()
  20445. ], BaseTexture.prototype, "isCube", void 0);
  20446. __decorate([
  20447. BABYLON.serialize()
  20448. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20449. return BaseTexture;
  20450. })();
  20451. BABYLON.BaseTexture = BaseTexture;
  20452. })(BABYLON || (BABYLON = {}));
  20453. var BABYLON;
  20454. (function (BABYLON) {
  20455. var Texture = (function (_super) {
  20456. __extends(Texture, _super);
  20457. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20458. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20459. if (onLoad === void 0) { onLoad = null; }
  20460. if (onError === void 0) { onError = null; }
  20461. if (buffer === void 0) { buffer = null; }
  20462. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20463. _super.call(this, scene);
  20464. this.uOffset = 0;
  20465. this.vOffset = 0;
  20466. this.uScale = 1.0;
  20467. this.vScale = 1.0;
  20468. this.uAng = 0;
  20469. this.vAng = 0;
  20470. this.wAng = 0;
  20471. this.name = url;
  20472. this.url = url;
  20473. this._noMipmap = noMipmap;
  20474. this._invertY = invertY;
  20475. this._samplingMode = samplingMode;
  20476. this._buffer = buffer;
  20477. this._deleteBuffer = deleteBuffer;
  20478. if (!url) {
  20479. return;
  20480. }
  20481. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20482. if (!this._texture) {
  20483. if (!scene.useDelayedTextureLoading) {
  20484. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20485. if (deleteBuffer) {
  20486. delete this._buffer;
  20487. }
  20488. }
  20489. else {
  20490. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20491. this._delayedOnLoad = onLoad;
  20492. this._delayedOnError = onError;
  20493. }
  20494. }
  20495. else {
  20496. BABYLON.Tools.SetImmediate(function () {
  20497. if (onLoad) {
  20498. onLoad();
  20499. }
  20500. });
  20501. }
  20502. }
  20503. Texture.prototype.delayLoad = function () {
  20504. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20505. return;
  20506. }
  20507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20508. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20509. if (!this._texture) {
  20510. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20511. if (this._deleteBuffer) {
  20512. delete this._buffer;
  20513. }
  20514. }
  20515. };
  20516. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20517. if (!this._texture) {
  20518. return;
  20519. }
  20520. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20521. };
  20522. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20523. x *= this.uScale;
  20524. y *= this.vScale;
  20525. x -= 0.5 * this.uScale;
  20526. y -= 0.5 * this.vScale;
  20527. z -= 0.5;
  20528. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20529. t.x += 0.5 * this.uScale + this.uOffset;
  20530. t.y += 0.5 * this.vScale + this.vOffset;
  20531. t.z += 0.5;
  20532. };
  20533. Texture.prototype.getTextureMatrix = function () {
  20534. if (this.uOffset === this._cachedUOffset &&
  20535. this.vOffset === this._cachedVOffset &&
  20536. this.uScale === this._cachedUScale &&
  20537. this.vScale === this._cachedVScale &&
  20538. this.uAng === this._cachedUAng &&
  20539. this.vAng === this._cachedVAng &&
  20540. this.wAng === this._cachedWAng) {
  20541. return this._cachedTextureMatrix;
  20542. }
  20543. this._cachedUOffset = this.uOffset;
  20544. this._cachedVOffset = this.vOffset;
  20545. this._cachedUScale = this.uScale;
  20546. this._cachedVScale = this.vScale;
  20547. this._cachedUAng = this.uAng;
  20548. this._cachedVAng = this.vAng;
  20549. this._cachedWAng = this.wAng;
  20550. if (!this._cachedTextureMatrix) {
  20551. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20552. this._rowGenerationMatrix = new BABYLON.Matrix();
  20553. this._t0 = BABYLON.Vector3.Zero();
  20554. this._t1 = BABYLON.Vector3.Zero();
  20555. this._t2 = BABYLON.Vector3.Zero();
  20556. }
  20557. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20558. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20559. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20560. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20561. this._t1.subtractInPlace(this._t0);
  20562. this._t2.subtractInPlace(this._t0);
  20563. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20564. this._cachedTextureMatrix.m[0] = this._t1.x;
  20565. this._cachedTextureMatrix.m[1] = this._t1.y;
  20566. this._cachedTextureMatrix.m[2] = this._t1.z;
  20567. this._cachedTextureMatrix.m[4] = this._t2.x;
  20568. this._cachedTextureMatrix.m[5] = this._t2.y;
  20569. this._cachedTextureMatrix.m[6] = this._t2.z;
  20570. this._cachedTextureMatrix.m[8] = this._t0.x;
  20571. this._cachedTextureMatrix.m[9] = this._t0.y;
  20572. this._cachedTextureMatrix.m[10] = this._t0.z;
  20573. return this._cachedTextureMatrix;
  20574. };
  20575. Texture.prototype.getReflectionTextureMatrix = function () {
  20576. if (this.uOffset === this._cachedUOffset &&
  20577. this.vOffset === this._cachedVOffset &&
  20578. this.uScale === this._cachedUScale &&
  20579. this.vScale === this._cachedVScale &&
  20580. this.coordinatesMode === this._cachedCoordinatesMode) {
  20581. return this._cachedTextureMatrix;
  20582. }
  20583. if (!this._cachedTextureMatrix) {
  20584. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20585. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20586. }
  20587. this._cachedCoordinatesMode = this.coordinatesMode;
  20588. switch (this.coordinatesMode) {
  20589. case Texture.PLANAR_MODE:
  20590. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20591. this._cachedTextureMatrix[0] = this.uScale;
  20592. this._cachedTextureMatrix[5] = this.vScale;
  20593. this._cachedTextureMatrix[12] = this.uOffset;
  20594. this._cachedTextureMatrix[13] = this.vOffset;
  20595. break;
  20596. case Texture.PROJECTION_MODE:
  20597. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20598. this._projectionModeMatrix.m[0] = 0.5;
  20599. this._projectionModeMatrix.m[5] = -0.5;
  20600. this._projectionModeMatrix.m[10] = 0.0;
  20601. this._projectionModeMatrix.m[12] = 0.5;
  20602. this._projectionModeMatrix.m[13] = 0.5;
  20603. this._projectionModeMatrix.m[14] = 1.0;
  20604. this._projectionModeMatrix.m[15] = 1.0;
  20605. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20606. break;
  20607. default:
  20608. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20609. break;
  20610. }
  20611. return this._cachedTextureMatrix;
  20612. };
  20613. Texture.prototype.clone = function () {
  20614. var _this = this;
  20615. return BABYLON.SerializationHelper.Clone(function () {
  20616. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20617. }, this);
  20618. };
  20619. // Statics
  20620. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20621. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20622. if (onLoad === void 0) { onLoad = null; }
  20623. if (onError === void 0) { onError = null; }
  20624. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20625. };
  20626. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20627. if (parsedTexture.isCube) {
  20628. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20629. }
  20630. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20631. return null;
  20632. }
  20633. var texture = BABYLON.SerializationHelper.Parse(function () {
  20634. if (parsedTexture.mirrorPlane) {
  20635. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20636. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20637. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20638. return mirrorTexture;
  20639. }
  20640. else if (parsedTexture.isRenderTarget) {
  20641. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20642. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20643. return renderTargetTexture;
  20644. }
  20645. else {
  20646. var texture;
  20647. if (parsedTexture.base64String) {
  20648. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20649. }
  20650. else {
  20651. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20652. }
  20653. return texture;
  20654. }
  20655. }, parsedTexture, scene);
  20656. // Animations
  20657. if (parsedTexture.animations) {
  20658. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20659. var parsedAnimation = parsedTexture.animations[animationIndex];
  20660. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20661. }
  20662. }
  20663. return texture;
  20664. };
  20665. // Constants
  20666. Texture.NEAREST_SAMPLINGMODE = 1;
  20667. Texture.BILINEAR_SAMPLINGMODE = 2;
  20668. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20669. Texture.EXPLICIT_MODE = 0;
  20670. Texture.SPHERICAL_MODE = 1;
  20671. Texture.PLANAR_MODE = 2;
  20672. Texture.CUBIC_MODE = 3;
  20673. Texture.PROJECTION_MODE = 4;
  20674. Texture.SKYBOX_MODE = 5;
  20675. Texture.INVCUBIC_MODE = 6;
  20676. Texture.EQUIRECTANGULAR_MODE = 7;
  20677. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20678. Texture.CLAMP_ADDRESSMODE = 0;
  20679. Texture.WRAP_ADDRESSMODE = 1;
  20680. Texture.MIRROR_ADDRESSMODE = 2;
  20681. __decorate([
  20682. BABYLON.serialize()
  20683. ], Texture.prototype, "url", void 0);
  20684. __decorate([
  20685. BABYLON.serialize()
  20686. ], Texture.prototype, "uOffset", void 0);
  20687. __decorate([
  20688. BABYLON.serialize()
  20689. ], Texture.prototype, "vOffset", void 0);
  20690. __decorate([
  20691. BABYLON.serialize()
  20692. ], Texture.prototype, "uScale", void 0);
  20693. __decorate([
  20694. BABYLON.serialize()
  20695. ], Texture.prototype, "vScale", void 0);
  20696. __decorate([
  20697. BABYLON.serialize()
  20698. ], Texture.prototype, "uAng", void 0);
  20699. __decorate([
  20700. BABYLON.serialize()
  20701. ], Texture.prototype, "vAng", void 0);
  20702. __decorate([
  20703. BABYLON.serialize()
  20704. ], Texture.prototype, "wAng", void 0);
  20705. return Texture;
  20706. })(BABYLON.BaseTexture);
  20707. BABYLON.Texture = Texture;
  20708. })(BABYLON || (BABYLON = {}));
  20709. var BABYLON;
  20710. (function (BABYLON) {
  20711. var CubeTexture = (function (_super) {
  20712. __extends(CubeTexture, _super);
  20713. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20714. _super.call(this, scene);
  20715. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20716. this.name = rootUrl;
  20717. this.url = rootUrl;
  20718. this._noMipmap = noMipmap;
  20719. this.hasAlpha = false;
  20720. if (!rootUrl && !files) {
  20721. return;
  20722. }
  20723. this._texture = this._getFromCache(rootUrl, noMipmap);
  20724. if (!files) {
  20725. if (!extensions) {
  20726. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20727. }
  20728. files = [];
  20729. for (var index = 0; index < extensions.length; index++) {
  20730. files.push(rootUrl + extensions[index]);
  20731. }
  20732. this._extensions = extensions;
  20733. }
  20734. this._files = files;
  20735. if (!this._texture) {
  20736. if (!scene.useDelayedTextureLoading) {
  20737. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20738. }
  20739. else {
  20740. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20741. }
  20742. }
  20743. this.isCube = true;
  20744. this._textureMatrix = BABYLON.Matrix.Identity();
  20745. }
  20746. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20747. return new CubeTexture("", scene, null, noMipmap, files);
  20748. };
  20749. // Methods
  20750. CubeTexture.prototype.delayLoad = function () {
  20751. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20752. return;
  20753. }
  20754. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20755. this._texture = this._getFromCache(this.url, this._noMipmap);
  20756. if (!this._texture) {
  20757. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20758. }
  20759. };
  20760. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20761. return this._textureMatrix;
  20762. };
  20763. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20764. var texture = BABYLON.SerializationHelper.Parse(function () {
  20765. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20766. }, parsedTexture, scene);
  20767. // Animations
  20768. if (parsedTexture.animations) {
  20769. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20770. var parsedAnimation = parsedTexture.animations[animationIndex];
  20771. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20772. }
  20773. }
  20774. return texture;
  20775. };
  20776. CubeTexture.prototype.clone = function () {
  20777. var _this = this;
  20778. return BABYLON.SerializationHelper.Clone(function () {
  20779. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20780. }, this);
  20781. };
  20782. return CubeTexture;
  20783. })(BABYLON.BaseTexture);
  20784. BABYLON.CubeTexture = CubeTexture;
  20785. })(BABYLON || (BABYLON = {}));
  20786. var BABYLON;
  20787. (function (BABYLON) {
  20788. var RenderTargetTexture = (function (_super) {
  20789. __extends(RenderTargetTexture, _super);
  20790. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20791. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20792. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20793. if (isCube === void 0) { isCube = false; }
  20794. _super.call(this, null, scene, !generateMipMaps);
  20795. this.isCube = isCube;
  20796. this.renderList = new Array();
  20797. this.renderParticles = true;
  20798. this.renderSprites = false;
  20799. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20800. this._currentRefreshId = -1;
  20801. this._refreshRate = 1;
  20802. this.name = name;
  20803. this.isRenderTarget = true;
  20804. this._size = size;
  20805. this._generateMipMaps = generateMipMaps;
  20806. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20807. if (isCube) {
  20808. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20809. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20810. this._textureMatrix = BABYLON.Matrix.Identity();
  20811. }
  20812. else {
  20813. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20814. }
  20815. // Rendering groups
  20816. this._renderingManager = new BABYLON.RenderingManager(scene);
  20817. }
  20818. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20819. get: function () {
  20820. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20821. },
  20822. enumerable: true,
  20823. configurable: true
  20824. });
  20825. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20826. get: function () {
  20827. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20828. },
  20829. enumerable: true,
  20830. configurable: true
  20831. });
  20832. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20833. get: function () {
  20834. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20835. },
  20836. enumerable: true,
  20837. configurable: true
  20838. });
  20839. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20840. this._currentRefreshId = -1;
  20841. };
  20842. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20843. get: function () {
  20844. return this._refreshRate;
  20845. },
  20846. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20847. set: function (value) {
  20848. this._refreshRate = value;
  20849. this.resetRefreshCounter();
  20850. },
  20851. enumerable: true,
  20852. configurable: true
  20853. });
  20854. RenderTargetTexture.prototype._shouldRender = function () {
  20855. if (this._currentRefreshId === -1) {
  20856. this._currentRefreshId = 1;
  20857. return true;
  20858. }
  20859. if (this.refreshRate === this._currentRefreshId) {
  20860. this._currentRefreshId = 1;
  20861. return true;
  20862. }
  20863. this._currentRefreshId++;
  20864. return false;
  20865. };
  20866. RenderTargetTexture.prototype.isReady = function () {
  20867. if (!this.getScene().renderTargetsEnabled) {
  20868. return false;
  20869. }
  20870. return _super.prototype.isReady.call(this);
  20871. };
  20872. RenderTargetTexture.prototype.getRenderSize = function () {
  20873. return this._size;
  20874. };
  20875. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20876. get: function () {
  20877. return true;
  20878. },
  20879. enumerable: true,
  20880. configurable: true
  20881. });
  20882. RenderTargetTexture.prototype.scale = function (ratio) {
  20883. var newSize = this._size * ratio;
  20884. this.resize(newSize, this._generateMipMaps);
  20885. };
  20886. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20887. if (this.isCube) {
  20888. return this._textureMatrix;
  20889. }
  20890. return _super.prototype.getReflectionTextureMatrix.call(this);
  20891. };
  20892. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20893. this.releaseInternalTexture();
  20894. if (this.isCube) {
  20895. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20896. }
  20897. else {
  20898. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20899. }
  20900. };
  20901. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20902. var scene = this.getScene();
  20903. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20904. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20905. }
  20906. if (this._waitingRenderList) {
  20907. this.renderList = [];
  20908. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20909. var id = this._waitingRenderList[index];
  20910. this.renderList.push(scene.getMeshByID(id));
  20911. }
  20912. delete this._waitingRenderList;
  20913. }
  20914. if (this.renderList && this.renderList.length === 0) {
  20915. return;
  20916. }
  20917. // Prepare renderingManager
  20918. this._renderingManager.reset();
  20919. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20920. var sceneRenderId = scene.getRenderId();
  20921. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20922. var mesh = currentRenderList[meshIndex];
  20923. if (mesh) {
  20924. if (!mesh.isReady()) {
  20925. // Reset _currentRefreshId
  20926. this.resetRefreshCounter();
  20927. continue;
  20928. }
  20929. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20930. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20931. mesh._activate(sceneRenderId);
  20932. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20933. var subMesh = mesh.subMeshes[subIndex];
  20934. scene._activeIndices += subMesh.indexCount;
  20935. this._renderingManager.dispatch(subMesh);
  20936. }
  20937. }
  20938. }
  20939. }
  20940. if (this.isCube) {
  20941. for (var face = 0; face < 6; face++) {
  20942. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20943. scene.incrementRenderId();
  20944. scene.resetCachedMaterial();
  20945. }
  20946. }
  20947. else {
  20948. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20949. }
  20950. if (this.onAfterUnbind) {
  20951. this.onAfterUnbind();
  20952. }
  20953. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20954. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20955. }
  20956. scene.resetCachedMaterial();
  20957. };
  20958. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20959. var scene = this.getScene();
  20960. var engine = scene.getEngine();
  20961. // Bind
  20962. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20963. if (this.isCube) {
  20964. engine.bindFramebuffer(this._texture, faceIndex);
  20965. }
  20966. else {
  20967. engine.bindFramebuffer(this._texture);
  20968. }
  20969. }
  20970. if (this.onBeforeRender) {
  20971. this.onBeforeRender(faceIndex);
  20972. }
  20973. // Clear
  20974. if (this.onClear) {
  20975. this.onClear(engine);
  20976. }
  20977. else {
  20978. engine.clear(scene.clearColor, true, true);
  20979. }
  20980. if (!this._doNotChangeAspectRatio) {
  20981. scene.updateTransformMatrix(true);
  20982. }
  20983. // Render
  20984. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20985. if (useCameraPostProcess) {
  20986. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20987. }
  20988. if (!this._doNotChangeAspectRatio) {
  20989. scene.updateTransformMatrix(true);
  20990. }
  20991. if (this.onAfterRender) {
  20992. this.onAfterRender(faceIndex);
  20993. }
  20994. // Dump ?
  20995. if (dumpForDebug) {
  20996. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20997. }
  20998. // Unbind
  20999. if (!this.isCube || faceIndex === 5) {
  21000. if (this.isCube) {
  21001. if (faceIndex === 5) {
  21002. engine.generateMipMapsForCubemap(this._texture);
  21003. }
  21004. }
  21005. engine.unBindFramebuffer(this._texture, this.isCube);
  21006. }
  21007. };
  21008. RenderTargetTexture.prototype.clone = function () {
  21009. var textureSize = this.getSize();
  21010. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21011. // Base texture
  21012. newTexture.hasAlpha = this.hasAlpha;
  21013. newTexture.level = this.level;
  21014. // RenderTarget Texture
  21015. newTexture.coordinatesMode = this.coordinatesMode;
  21016. newTexture.renderList = this.renderList.slice(0);
  21017. return newTexture;
  21018. };
  21019. RenderTargetTexture.prototype.serialize = function () {
  21020. if (!this.name) {
  21021. return null;
  21022. }
  21023. var serializationObject = _super.prototype.serialize.call(this);
  21024. serializationObject.renderTargetSize = this.getRenderSize();
  21025. serializationObject.renderList = [];
  21026. for (var index = 0; index < this.renderList.length; index++) {
  21027. serializationObject.renderList.push(this.renderList[index].id);
  21028. }
  21029. return serializationObject;
  21030. };
  21031. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  21032. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  21033. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  21034. return RenderTargetTexture;
  21035. })(BABYLON.Texture);
  21036. BABYLON.RenderTargetTexture = RenderTargetTexture;
  21037. })(BABYLON || (BABYLON = {}));
  21038. var BABYLON;
  21039. (function (BABYLON) {
  21040. var ProceduralTexture = (function (_super) {
  21041. __extends(ProceduralTexture, _super);
  21042. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  21043. if (generateMipMaps === void 0) { generateMipMaps = true; }
  21044. if (isCube === void 0) { isCube = false; }
  21045. _super.call(this, null, scene, !generateMipMaps);
  21046. this.isCube = isCube;
  21047. this.isEnabled = true;
  21048. this._currentRefreshId = -1;
  21049. this._refreshRate = 1;
  21050. this._vertexDeclaration = [2];
  21051. this._vertexStrideSize = 2 * 4;
  21052. this._uniforms = new Array();
  21053. this._samplers = new Array();
  21054. this._textures = new Array();
  21055. this._floats = new Array();
  21056. this._floatsArrays = {};
  21057. this._colors3 = new Array();
  21058. this._colors4 = new Array();
  21059. this._vectors2 = new Array();
  21060. this._vectors3 = new Array();
  21061. this._matrices = new Array();
  21062. this._fallbackTextureUsed = false;
  21063. scene._proceduralTextures.push(this);
  21064. this.name = name;
  21065. this.isRenderTarget = true;
  21066. this._size = size;
  21067. this._generateMipMaps = generateMipMaps;
  21068. this.setFragment(fragment);
  21069. this._fallbackTexture = fallbackTexture;
  21070. if (isCube) {
  21071. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  21072. this.setFloat("face", 0);
  21073. }
  21074. else {
  21075. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  21076. }
  21077. // VBO
  21078. var vertices = [];
  21079. vertices.push(1, 1);
  21080. vertices.push(-1, 1);
  21081. vertices.push(-1, -1);
  21082. vertices.push(1, -1);
  21083. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21084. // Indices
  21085. var indices = [];
  21086. indices.push(0);
  21087. indices.push(1);
  21088. indices.push(2);
  21089. indices.push(0);
  21090. indices.push(2);
  21091. indices.push(3);
  21092. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21093. }
  21094. ProceduralTexture.prototype.reset = function () {
  21095. if (this._effect === undefined) {
  21096. return;
  21097. }
  21098. var engine = this.getScene().getEngine();
  21099. engine._releaseEffect(this._effect);
  21100. };
  21101. ProceduralTexture.prototype.isReady = function () {
  21102. var _this = this;
  21103. var engine = this.getScene().getEngine();
  21104. var shaders;
  21105. if (!this._fragment) {
  21106. return false;
  21107. }
  21108. if (this._fallbackTextureUsed) {
  21109. return true;
  21110. }
  21111. if (this._fragment.fragmentElement !== undefined) {
  21112. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  21113. }
  21114. else {
  21115. shaders = { vertex: "procedural", fragment: this._fragment };
  21116. }
  21117. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  21118. _this.releaseInternalTexture();
  21119. if (_this._fallbackTexture) {
  21120. _this._texture = _this._fallbackTexture._texture;
  21121. _this._texture.references++;
  21122. }
  21123. _this._fallbackTextureUsed = true;
  21124. });
  21125. return this._effect.isReady();
  21126. };
  21127. ProceduralTexture.prototype.resetRefreshCounter = function () {
  21128. this._currentRefreshId = -1;
  21129. };
  21130. ProceduralTexture.prototype.setFragment = function (fragment) {
  21131. this._fragment = fragment;
  21132. };
  21133. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  21134. get: function () {
  21135. return this._refreshRate;
  21136. },
  21137. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  21138. set: function (value) {
  21139. this._refreshRate = value;
  21140. this.resetRefreshCounter();
  21141. },
  21142. enumerable: true,
  21143. configurable: true
  21144. });
  21145. ProceduralTexture.prototype._shouldRender = function () {
  21146. if (!this.isEnabled || !this.isReady() || !this._texture) {
  21147. return false;
  21148. }
  21149. if (this._fallbackTextureUsed) {
  21150. return false;
  21151. }
  21152. if (this._currentRefreshId === -1) {
  21153. this._currentRefreshId = 1;
  21154. return true;
  21155. }
  21156. if (this.refreshRate === this._currentRefreshId) {
  21157. this._currentRefreshId = 1;
  21158. return true;
  21159. }
  21160. this._currentRefreshId++;
  21161. return false;
  21162. };
  21163. ProceduralTexture.prototype.getRenderSize = function () {
  21164. return this._size;
  21165. };
  21166. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  21167. if (this._fallbackTextureUsed) {
  21168. return;
  21169. }
  21170. this.releaseInternalTexture();
  21171. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21172. };
  21173. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21174. if (this._uniforms.indexOf(uniformName) === -1) {
  21175. this._uniforms.push(uniformName);
  21176. }
  21177. };
  21178. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21179. if (this._samplers.indexOf(name) === -1) {
  21180. this._samplers.push(name);
  21181. }
  21182. this._textures[name] = texture;
  21183. return this;
  21184. };
  21185. ProceduralTexture.prototype.setFloat = function (name, value) {
  21186. this._checkUniform(name);
  21187. this._floats[name] = value;
  21188. return this;
  21189. };
  21190. ProceduralTexture.prototype.setFloats = function (name, value) {
  21191. this._checkUniform(name);
  21192. this._floatsArrays[name] = value;
  21193. return this;
  21194. };
  21195. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21196. this._checkUniform(name);
  21197. this._colors3[name] = value;
  21198. return this;
  21199. };
  21200. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21201. this._checkUniform(name);
  21202. this._colors4[name] = value;
  21203. return this;
  21204. };
  21205. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21206. this._checkUniform(name);
  21207. this._vectors2[name] = value;
  21208. return this;
  21209. };
  21210. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21211. this._checkUniform(name);
  21212. this._vectors3[name] = value;
  21213. return this;
  21214. };
  21215. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21216. this._checkUniform(name);
  21217. this._matrices[name] = value;
  21218. return this;
  21219. };
  21220. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21221. var scene = this.getScene();
  21222. var engine = scene.getEngine();
  21223. // Render
  21224. engine.enableEffect(this._effect);
  21225. engine.setState(false);
  21226. // Texture
  21227. for (var name in this._textures) {
  21228. this._effect.setTexture(name, this._textures[name]);
  21229. }
  21230. // Float
  21231. for (name in this._floats) {
  21232. this._effect.setFloat(name, this._floats[name]);
  21233. }
  21234. // Floats
  21235. for (name in this._floatsArrays) {
  21236. this._effect.setArray(name, this._floatsArrays[name]);
  21237. }
  21238. // Color3
  21239. for (name in this._colors3) {
  21240. this._effect.setColor3(name, this._colors3[name]);
  21241. }
  21242. // Color4
  21243. for (name in this._colors4) {
  21244. var color = this._colors4[name];
  21245. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21246. }
  21247. // Vector2
  21248. for (name in this._vectors2) {
  21249. this._effect.setVector2(name, this._vectors2[name]);
  21250. }
  21251. // Vector3
  21252. for (name in this._vectors3) {
  21253. this._effect.setVector3(name, this._vectors3[name]);
  21254. }
  21255. // Matrix
  21256. for (name in this._matrices) {
  21257. this._effect.setMatrix(name, this._matrices[name]);
  21258. }
  21259. // VBOs
  21260. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21261. if (this.isCube) {
  21262. for (var face = 0; face < 6; face++) {
  21263. engine.bindFramebuffer(this._texture, face);
  21264. this._effect.setFloat("face", face);
  21265. // Clear
  21266. engine.clear(scene.clearColor, true, true);
  21267. // Draw order
  21268. engine.draw(true, 0, 6);
  21269. // Mipmaps
  21270. if (face === 5) {
  21271. engine.generateMipMapsForCubemap(this._texture);
  21272. }
  21273. }
  21274. }
  21275. else {
  21276. engine.bindFramebuffer(this._texture);
  21277. // Clear
  21278. engine.clear(scene.clearColor, true, true);
  21279. // Draw order
  21280. engine.draw(true, 0, 6);
  21281. }
  21282. // Unbind
  21283. engine.unBindFramebuffer(this._texture, this.isCube);
  21284. if (this.onGenerated) {
  21285. this.onGenerated();
  21286. }
  21287. };
  21288. ProceduralTexture.prototype.clone = function () {
  21289. var textureSize = this.getSize();
  21290. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21291. // Base texture
  21292. newTexture.hasAlpha = this.hasAlpha;
  21293. newTexture.level = this.level;
  21294. // RenderTarget Texture
  21295. newTexture.coordinatesMode = this.coordinatesMode;
  21296. return newTexture;
  21297. };
  21298. ProceduralTexture.prototype.dispose = function () {
  21299. var index = this.getScene()._proceduralTextures.indexOf(this);
  21300. if (index >= 0) {
  21301. this.getScene()._proceduralTextures.splice(index, 1);
  21302. }
  21303. _super.prototype.dispose.call(this);
  21304. };
  21305. return ProceduralTexture;
  21306. })(BABYLON.Texture);
  21307. BABYLON.ProceduralTexture = ProceduralTexture;
  21308. })(BABYLON || (BABYLON = {}));
  21309. var BABYLON;
  21310. (function (BABYLON) {
  21311. var MirrorTexture = (function (_super) {
  21312. __extends(MirrorTexture, _super);
  21313. function MirrorTexture(name, size, scene, generateMipMaps) {
  21314. var _this = this;
  21315. _super.call(this, name, size, scene, generateMipMaps, true);
  21316. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21317. this._transformMatrix = BABYLON.Matrix.Zero();
  21318. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21319. this.onBeforeRender = function () {
  21320. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21321. _this._savedViewMatrix = scene.getViewMatrix();
  21322. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21323. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21324. scene.clipPlane = _this.mirrorPlane;
  21325. scene.getEngine().cullBackFaces = false;
  21326. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21327. };
  21328. this.onAfterRender = function () {
  21329. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21330. scene.getEngine().cullBackFaces = true;
  21331. scene._mirroredCameraPosition = null;
  21332. delete scene.clipPlane;
  21333. };
  21334. }
  21335. MirrorTexture.prototype.clone = function () {
  21336. var textureSize = this.getSize();
  21337. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21338. // Base texture
  21339. newTexture.hasAlpha = this.hasAlpha;
  21340. newTexture.level = this.level;
  21341. // Mirror Texture
  21342. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21343. newTexture.renderList = this.renderList.slice(0);
  21344. return newTexture;
  21345. };
  21346. MirrorTexture.prototype.serialize = function () {
  21347. if (!this.name) {
  21348. return null;
  21349. }
  21350. var serializationObject = _super.prototype.serialize.call(this);
  21351. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21352. return serializationObject;
  21353. };
  21354. return MirrorTexture;
  21355. })(BABYLON.RenderTargetTexture);
  21356. BABYLON.MirrorTexture = MirrorTexture;
  21357. })(BABYLON || (BABYLON = {}));
  21358. var BABYLON;
  21359. (function (BABYLON) {
  21360. /**
  21361. * Creates a refraction texture used by refraction channel of the standard material.
  21362. * @param name the texture name
  21363. * @param size size of the underlying texture
  21364. * @param scene root scene
  21365. */
  21366. var RefractionTexture = (function (_super) {
  21367. __extends(RefractionTexture, _super);
  21368. function RefractionTexture(name, size, scene, generateMipMaps) {
  21369. var _this = this;
  21370. _super.call(this, name, size, scene, generateMipMaps, true);
  21371. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21372. this.depth = 2.0;
  21373. this.onBeforeRender = function () {
  21374. scene.clipPlane = _this.refractionPlane;
  21375. };
  21376. this.onAfterRender = function () {
  21377. delete scene.clipPlane;
  21378. };
  21379. }
  21380. RefractionTexture.prototype.clone = function () {
  21381. var textureSize = this.getSize();
  21382. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21383. // Base texture
  21384. newTexture.hasAlpha = this.hasAlpha;
  21385. newTexture.level = this.level;
  21386. // Refraction Texture
  21387. newTexture.refractionPlane = this.refractionPlane.clone();
  21388. newTexture.renderList = this.renderList.slice(0);
  21389. newTexture.depth = this.depth;
  21390. return newTexture;
  21391. };
  21392. RefractionTexture.prototype.serialize = function () {
  21393. if (!this.name) {
  21394. return null;
  21395. }
  21396. var serializationObject = _super.prototype.serialize.call(this);
  21397. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21398. serializationObject.depth = this.depth;
  21399. return serializationObject;
  21400. };
  21401. return RefractionTexture;
  21402. })(BABYLON.RenderTargetTexture);
  21403. BABYLON.RefractionTexture = RefractionTexture;
  21404. })(BABYLON || (BABYLON = {}));
  21405. var BABYLON;
  21406. (function (BABYLON) {
  21407. var DynamicTexture = (function (_super) {
  21408. __extends(DynamicTexture, _super);
  21409. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21411. _super.call(this, null, scene, !generateMipMaps);
  21412. this.name = name;
  21413. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21414. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21415. this._generateMipMaps = generateMipMaps;
  21416. if (options.getContext) {
  21417. this._canvas = options;
  21418. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21419. }
  21420. else {
  21421. this._canvas = document.createElement("canvas");
  21422. if (options.width) {
  21423. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21424. }
  21425. else {
  21426. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21427. }
  21428. }
  21429. var textureSize = this.getSize();
  21430. this._canvas.width = textureSize.width;
  21431. this._canvas.height = textureSize.height;
  21432. this._context = this._canvas.getContext("2d");
  21433. }
  21434. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21435. get: function () {
  21436. return true;
  21437. },
  21438. enumerable: true,
  21439. configurable: true
  21440. });
  21441. DynamicTexture.prototype.scale = function (ratio) {
  21442. var textureSize = this.getSize();
  21443. textureSize.width *= ratio;
  21444. textureSize.height *= ratio;
  21445. this._canvas.width = textureSize.width;
  21446. this._canvas.height = textureSize.height;
  21447. this.releaseInternalTexture();
  21448. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21449. };
  21450. DynamicTexture.prototype.getContext = function () {
  21451. return this._context;
  21452. };
  21453. DynamicTexture.prototype.clear = function () {
  21454. var size = this.getSize();
  21455. this._context.fillRect(0, 0, size.width, size.height);
  21456. };
  21457. DynamicTexture.prototype.update = function (invertY) {
  21458. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21459. };
  21460. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21461. if (update === void 0) { update = true; }
  21462. var size = this.getSize();
  21463. if (clearColor) {
  21464. this._context.fillStyle = clearColor;
  21465. this._context.fillRect(0, 0, size.width, size.height);
  21466. }
  21467. this._context.font = font;
  21468. if (x === null) {
  21469. var textSize = this._context.measureText(text);
  21470. x = (size.width - textSize.width) / 2;
  21471. }
  21472. this._context.fillStyle = color;
  21473. this._context.fillText(text, x, y);
  21474. if (update) {
  21475. this.update(invertY);
  21476. }
  21477. };
  21478. DynamicTexture.prototype.clone = function () {
  21479. var textureSize = this.getSize();
  21480. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21481. // Base texture
  21482. newTexture.hasAlpha = this.hasAlpha;
  21483. newTexture.level = this.level;
  21484. // Dynamic Texture
  21485. newTexture.wrapU = this.wrapU;
  21486. newTexture.wrapV = this.wrapV;
  21487. return newTexture;
  21488. };
  21489. return DynamicTexture;
  21490. })(BABYLON.Texture);
  21491. BABYLON.DynamicTexture = DynamicTexture;
  21492. })(BABYLON || (BABYLON = {}));
  21493. var BABYLON;
  21494. (function (BABYLON) {
  21495. var VideoTexture = (function (_super) {
  21496. __extends(VideoTexture, _super);
  21497. /**
  21498. * Creates a video texture.
  21499. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21500. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21501. * @param {BABYLON.Scene} scene is obviously the current scene.
  21502. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21503. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21504. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21505. */
  21506. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21507. var _this = this;
  21508. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21509. if (invertY === void 0) { invertY = false; }
  21510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21511. _super.call(this, null, scene, !generateMipMaps, invertY);
  21512. this._autoLaunch = true;
  21513. var urls;
  21514. this.name = name;
  21515. if (urlsOrVideo instanceof HTMLVideoElement) {
  21516. this.video = urlsOrVideo;
  21517. }
  21518. else {
  21519. urls = urlsOrVideo;
  21520. this.video = document.createElement("video");
  21521. this.video.autoplay = false;
  21522. this.video.loop = true;
  21523. }
  21524. this._generateMipMaps = generateMipMaps;
  21525. this._samplingMode = samplingMode;
  21526. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21527. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21528. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21529. }
  21530. else {
  21531. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21532. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21533. this._generateMipMaps = false;
  21534. }
  21535. if (urls) {
  21536. this.video.addEventListener("canplaythrough", function () {
  21537. _this._createTexture();
  21538. });
  21539. urls.forEach(function (url) {
  21540. var source = document.createElement("source");
  21541. source.src = url;
  21542. _this.video.appendChild(source);
  21543. });
  21544. }
  21545. else {
  21546. this._createTexture();
  21547. }
  21548. this._lastUpdate = BABYLON.Tools.Now;
  21549. }
  21550. VideoTexture.prototype._createTexture = function () {
  21551. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21552. this._texture.isReady = true;
  21553. };
  21554. VideoTexture.prototype.update = function () {
  21555. if (this._autoLaunch) {
  21556. this._autoLaunch = false;
  21557. this.video.play();
  21558. }
  21559. var now = BABYLON.Tools.Now;
  21560. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21561. return false;
  21562. }
  21563. this._lastUpdate = now;
  21564. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21565. return true;
  21566. };
  21567. return VideoTexture;
  21568. })(BABYLON.Texture);
  21569. BABYLON.VideoTexture = VideoTexture;
  21570. })(BABYLON || (BABYLON = {}));
  21571. var BABYLON;
  21572. (function (BABYLON) {
  21573. var CustomProceduralTexture = (function (_super) {
  21574. __extends(CustomProceduralTexture, _super);
  21575. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21576. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21577. this._animate = true;
  21578. this._time = 0;
  21579. this._texturePath = texturePath;
  21580. //Try to load json
  21581. this.loadJson(texturePath);
  21582. this.refreshRate = 1;
  21583. }
  21584. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21585. var _this = this;
  21586. var that = this;
  21587. function noConfigFile() {
  21588. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21589. try {
  21590. that.setFragment(that._texturePath);
  21591. }
  21592. catch (ex) {
  21593. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21594. }
  21595. }
  21596. var configFileUrl = jsonUrl + "/config.json";
  21597. var xhr = new XMLHttpRequest();
  21598. xhr.open("GET", configFileUrl, true);
  21599. xhr.addEventListener("load", function () {
  21600. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21601. try {
  21602. _this._config = JSON.parse(xhr.response);
  21603. _this.updateShaderUniforms();
  21604. _this.updateTextures();
  21605. _this.setFragment(_this._texturePath + "/custom");
  21606. _this._animate = _this._config.animate;
  21607. _this.refreshRate = _this._config.refreshrate;
  21608. }
  21609. catch (ex) {
  21610. noConfigFile();
  21611. }
  21612. }
  21613. else {
  21614. noConfigFile();
  21615. }
  21616. }, false);
  21617. xhr.addEventListener("error", function () {
  21618. noConfigFile();
  21619. }, false);
  21620. try {
  21621. xhr.send();
  21622. }
  21623. catch (ex) {
  21624. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21625. }
  21626. };
  21627. CustomProceduralTexture.prototype.isReady = function () {
  21628. if (!_super.prototype.isReady.call(this)) {
  21629. return false;
  21630. }
  21631. for (var name in this._textures) {
  21632. var texture = this._textures[name];
  21633. if (!texture.isReady()) {
  21634. return false;
  21635. }
  21636. }
  21637. return true;
  21638. };
  21639. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21640. if (this._animate) {
  21641. this._time += this.getScene().getAnimationRatio() * 0.03;
  21642. this.updateShaderUniforms();
  21643. }
  21644. _super.prototype.render.call(this, useCameraPostProcess);
  21645. };
  21646. CustomProceduralTexture.prototype.updateTextures = function () {
  21647. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21648. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21649. }
  21650. };
  21651. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21652. if (this._config) {
  21653. for (var j = 0; j < this._config.uniforms.length; j++) {
  21654. var uniform = this._config.uniforms[j];
  21655. switch (uniform.type) {
  21656. case "float":
  21657. this.setFloat(uniform.name, uniform.value);
  21658. break;
  21659. case "color3":
  21660. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21661. break;
  21662. case "color4":
  21663. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21664. break;
  21665. case "vector2":
  21666. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21667. break;
  21668. case "vector3":
  21669. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21670. break;
  21671. }
  21672. }
  21673. }
  21674. this.setFloat("time", this._time);
  21675. };
  21676. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21677. get: function () {
  21678. return this._animate;
  21679. },
  21680. set: function (value) {
  21681. this._animate = value;
  21682. },
  21683. enumerable: true,
  21684. configurable: true
  21685. });
  21686. return CustomProceduralTexture;
  21687. })(BABYLON.ProceduralTexture);
  21688. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21689. })(BABYLON || (BABYLON = {}));
  21690. var BABYLON;
  21691. (function (BABYLON) {
  21692. var EffectFallbacks = (function () {
  21693. function EffectFallbacks() {
  21694. this._defines = {};
  21695. this._currentRank = 32;
  21696. this._maxRank = -1;
  21697. }
  21698. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21699. if (!this._defines[rank]) {
  21700. if (rank < this._currentRank) {
  21701. this._currentRank = rank;
  21702. }
  21703. if (rank > this._maxRank) {
  21704. this._maxRank = rank;
  21705. }
  21706. this._defines[rank] = new Array();
  21707. }
  21708. this._defines[rank].push(define);
  21709. };
  21710. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21711. this._meshRank = rank;
  21712. this._mesh = mesh;
  21713. if (rank > this._maxRank) {
  21714. this._maxRank = rank;
  21715. }
  21716. };
  21717. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21718. get: function () {
  21719. return this._currentRank <= this._maxRank;
  21720. },
  21721. enumerable: true,
  21722. configurable: true
  21723. });
  21724. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21725. var currentFallbacks = this._defines[this._currentRank];
  21726. for (var index = 0; index < currentFallbacks.length; index++) {
  21727. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21728. }
  21729. if (this._mesh && this._currentRank === this._meshRank) {
  21730. this._mesh.computeBonesUsingShaders = false;
  21731. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21732. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21733. }
  21734. this._currentRank++;
  21735. return currentDefines;
  21736. };
  21737. return EffectFallbacks;
  21738. })();
  21739. BABYLON.EffectFallbacks = EffectFallbacks;
  21740. var Effect = (function () {
  21741. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21742. var _this = this;
  21743. this._isReady = false;
  21744. this._compilationError = "";
  21745. this._valueCache = [];
  21746. this._engine = engine;
  21747. this.name = baseName;
  21748. this.defines = defines;
  21749. this._uniformsNames = uniformsNames.concat(samplers);
  21750. this._samplers = samplers;
  21751. this._attributesNames = attributesNames;
  21752. this.onError = onError;
  21753. this.onCompiled = onCompiled;
  21754. this._indexParameters = indexParameters;
  21755. var vertexSource;
  21756. var fragmentSource;
  21757. if (baseName.vertexElement) {
  21758. vertexSource = document.getElementById(baseName.vertexElement);
  21759. if (!vertexSource) {
  21760. vertexSource = baseName.vertexElement;
  21761. }
  21762. }
  21763. else {
  21764. vertexSource = baseName.vertex || baseName;
  21765. }
  21766. if (baseName.fragmentElement) {
  21767. fragmentSource = document.getElementById(baseName.fragmentElement);
  21768. if (!fragmentSource) {
  21769. fragmentSource = baseName.fragmentElement;
  21770. }
  21771. }
  21772. else {
  21773. fragmentSource = baseName.fragment || baseName;
  21774. }
  21775. this._loadVertexShader(vertexSource, function (vertexCode) {
  21776. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21777. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21778. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21779. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21780. });
  21781. });
  21782. });
  21783. });
  21784. }
  21785. // Properties
  21786. Effect.prototype.isReady = function () {
  21787. return this._isReady;
  21788. };
  21789. Effect.prototype.getProgram = function () {
  21790. return this._program;
  21791. };
  21792. Effect.prototype.getAttributesNames = function () {
  21793. return this._attributesNames;
  21794. };
  21795. Effect.prototype.getAttributeLocation = function (index) {
  21796. return this._attributes[index];
  21797. };
  21798. Effect.prototype.getAttributeLocationByName = function (name) {
  21799. var index = this._attributesNames.indexOf(name);
  21800. return this._attributes[index];
  21801. };
  21802. Effect.prototype.getAttributesCount = function () {
  21803. return this._attributes.length;
  21804. };
  21805. Effect.prototype.getUniformIndex = function (uniformName) {
  21806. return this._uniformsNames.indexOf(uniformName);
  21807. };
  21808. Effect.prototype.getUniform = function (uniformName) {
  21809. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21810. };
  21811. Effect.prototype.getSamplers = function () {
  21812. return this._samplers;
  21813. };
  21814. Effect.prototype.getCompilationError = function () {
  21815. return this._compilationError;
  21816. };
  21817. // Methods
  21818. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21819. // DOM element ?
  21820. if (vertex instanceof HTMLElement) {
  21821. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21822. callback(vertexCode);
  21823. return;
  21824. }
  21825. // Is in local store ?
  21826. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21827. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21828. return;
  21829. }
  21830. var vertexShaderUrl;
  21831. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21832. vertexShaderUrl = vertex;
  21833. }
  21834. else {
  21835. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21836. }
  21837. // Vertex shader
  21838. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21839. };
  21840. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21841. // DOM element ?
  21842. if (fragment instanceof HTMLElement) {
  21843. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21844. callback(fragmentCode);
  21845. return;
  21846. }
  21847. // Is in local store ?
  21848. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21849. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21850. return;
  21851. }
  21852. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21853. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21854. return;
  21855. }
  21856. var fragmentShaderUrl;
  21857. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21858. fragmentShaderUrl = fragment;
  21859. }
  21860. else {
  21861. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21862. }
  21863. // Fragment shader
  21864. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21865. };
  21866. Effect.prototype._dumpShadersName = function () {
  21867. if (this.name.vertexElement) {
  21868. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21869. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21870. }
  21871. else if (this.name.vertex) {
  21872. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21873. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21874. }
  21875. else {
  21876. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21877. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21878. }
  21879. };
  21880. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21881. var _this = this;
  21882. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21883. var match = regex.exec(sourceCode);
  21884. var returnValue = new String(sourceCode);
  21885. while (match != null) {
  21886. var includeFile = match[1];
  21887. if (Effect.IncludesShadersStore[includeFile]) {
  21888. // Substitution
  21889. var includeContent = Effect.IncludesShadersStore[includeFile];
  21890. if (match[2]) {
  21891. var splits = match[3].split(",");
  21892. for (var index = 0; index < splits.length; index += 2) {
  21893. var source = new RegExp(splits[index], "g");
  21894. var dest = splits[index + 1];
  21895. includeContent = includeContent.replace(source, dest);
  21896. }
  21897. }
  21898. if (match[4]) {
  21899. var indexString = match[5];
  21900. if (indexString.indexOf("..") !== -1) {
  21901. var indexSplits = indexString.split("..");
  21902. var minIndex = parseInt(indexSplits[0]);
  21903. var maxIndex = parseInt(indexSplits[1]);
  21904. var sourceIncludeContent = includeContent.slice(0);
  21905. includeContent = "";
  21906. if (isNaN(maxIndex)) {
  21907. maxIndex = this._indexParameters[indexSplits[1]];
  21908. }
  21909. for (var i = minIndex; i <= maxIndex; i++) {
  21910. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21911. }
  21912. }
  21913. else {
  21914. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21915. }
  21916. }
  21917. // Replace
  21918. returnValue = returnValue.replace(match[0], includeContent);
  21919. }
  21920. else {
  21921. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21922. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21923. Effect.IncludesShadersStore[includeFile] = fileContent;
  21924. _this._processIncludes(returnValue, callback);
  21925. });
  21926. return;
  21927. }
  21928. match = regex.exec(sourceCode);
  21929. }
  21930. callback(returnValue);
  21931. };
  21932. Effect.prototype._processPrecision = function (source) {
  21933. if (source.indexOf("precision highp float") === -1) {
  21934. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21935. source = "precision mediump float;\n" + source;
  21936. }
  21937. else {
  21938. source = "precision highp float;\n" + source;
  21939. }
  21940. }
  21941. else {
  21942. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21943. source = source.replace("precision highp float", "precision mediump float");
  21944. }
  21945. }
  21946. return source;
  21947. };
  21948. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21949. try {
  21950. var engine = this._engine;
  21951. // Precision
  21952. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21953. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21954. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21955. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21956. this._attributes = engine.getAttributes(this._program, attributesNames);
  21957. for (var index = 0; index < this._samplers.length; index++) {
  21958. var sampler = this.getUniform(this._samplers[index]);
  21959. if (sampler == null) {
  21960. this._samplers.splice(index, 1);
  21961. index--;
  21962. }
  21963. }
  21964. engine.bindSamplers(this);
  21965. this._isReady = true;
  21966. if (this.onCompiled) {
  21967. this.onCompiled(this);
  21968. }
  21969. }
  21970. catch (e) {
  21971. // Is it a problem with precision?
  21972. if (e.message.indexOf("highp") !== -1) {
  21973. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21974. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21975. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21976. return;
  21977. }
  21978. // Let's go through fallbacks then
  21979. if (fallbacks && fallbacks.isMoreFallbacks) {
  21980. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21981. this._dumpShadersName();
  21982. defines = fallbacks.reduce(defines);
  21983. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21984. }
  21985. else {
  21986. BABYLON.Tools.Error("Unable to compile effect: ");
  21987. this._dumpShadersName();
  21988. BABYLON.Tools.Error("Defines: " + defines);
  21989. BABYLON.Tools.Error("Error: " + e.message);
  21990. this._compilationError = e.message;
  21991. if (this.onError) {
  21992. this.onError(this, this._compilationError);
  21993. }
  21994. }
  21995. }
  21996. };
  21997. Object.defineProperty(Effect.prototype, "isSupported", {
  21998. get: function () {
  21999. return this._compilationError === "";
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. Effect.prototype._bindTexture = function (channel, texture) {
  22005. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22006. };
  22007. Effect.prototype.setTexture = function (channel, texture) {
  22008. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  22009. };
  22010. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22011. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22012. };
  22013. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22014. if (!this._valueCache[uniformName]) {
  22015. this._valueCache[uniformName] = new BABYLON.Matrix();
  22016. }
  22017. for (var index = 0; index < 16; index++) {
  22018. this._valueCache[uniformName].m[index] = matrix.m[index];
  22019. }
  22020. };
  22021. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22022. if (!this._valueCache[uniformName]) {
  22023. this._valueCache[uniformName] = [x, y];
  22024. return;
  22025. }
  22026. this._valueCache[uniformName][0] = x;
  22027. this._valueCache[uniformName][1] = y;
  22028. };
  22029. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22030. if (!this._valueCache[uniformName]) {
  22031. this._valueCache[uniformName] = [x, y, z];
  22032. return;
  22033. }
  22034. this._valueCache[uniformName][0] = x;
  22035. this._valueCache[uniformName][1] = y;
  22036. this._valueCache[uniformName][2] = z;
  22037. };
  22038. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22039. if (!this._valueCache[uniformName]) {
  22040. this._valueCache[uniformName] = [x, y, z, w];
  22041. return;
  22042. }
  22043. this._valueCache[uniformName][0] = x;
  22044. this._valueCache[uniformName][1] = y;
  22045. this._valueCache[uniformName][2] = z;
  22046. this._valueCache[uniformName][3] = w;
  22047. };
  22048. Effect.prototype.setArray = function (uniformName, array) {
  22049. this._engine.setArray(this.getUniform(uniformName), array);
  22050. return this;
  22051. };
  22052. Effect.prototype.setArray2 = function (uniformName, array) {
  22053. this._engine.setArray2(this.getUniform(uniformName), array);
  22054. return this;
  22055. };
  22056. Effect.prototype.setArray3 = function (uniformName, array) {
  22057. this._engine.setArray3(this.getUniform(uniformName), array);
  22058. return this;
  22059. };
  22060. Effect.prototype.setArray4 = function (uniformName, array) {
  22061. this._engine.setArray4(this.getUniform(uniformName), array);
  22062. return this;
  22063. };
  22064. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22065. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22066. return this;
  22067. };
  22068. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22069. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  22070. // return this;
  22071. // this._cacheMatrix(uniformName, matrix);
  22072. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22073. return this;
  22074. };
  22075. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22076. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22077. return this;
  22078. };
  22079. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  22080. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  22081. return this;
  22082. };
  22083. Effect.prototype.setFloat = function (uniformName, value) {
  22084. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  22085. return this;
  22086. this._valueCache[uniformName] = value;
  22087. this._engine.setFloat(this.getUniform(uniformName), value);
  22088. return this;
  22089. };
  22090. Effect.prototype.setBool = function (uniformName, bool) {
  22091. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  22092. return this;
  22093. this._valueCache[uniformName] = bool;
  22094. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22095. return this;
  22096. };
  22097. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22098. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  22099. return this;
  22100. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  22101. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22102. return this;
  22103. };
  22104. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22105. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  22106. return this;
  22107. this._cacheFloat2(uniformName, x, y);
  22108. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22109. return this;
  22110. };
  22111. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22112. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  22113. return this;
  22114. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  22115. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22116. return this;
  22117. };
  22118. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22119. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  22120. return this;
  22121. this._cacheFloat3(uniformName, x, y, z);
  22122. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22123. return this;
  22124. };
  22125. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22126. 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)
  22127. return this;
  22128. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  22129. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22130. return this;
  22131. };
  22132. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22133. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  22134. return this;
  22135. this._cacheFloat4(uniformName, x, y, z, w);
  22136. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22137. return this;
  22138. };
  22139. Effect.prototype.setColor3 = function (uniformName, color3) {
  22140. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  22141. return this;
  22142. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  22143. this._engine.setColor3(this.getUniform(uniformName), color3);
  22144. return this;
  22145. };
  22146. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22147. 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)
  22148. return this;
  22149. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  22150. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22151. return this;
  22152. };
  22153. // Statics
  22154. Effect.ShadersStore = {};
  22155. Effect.IncludesShadersStore = {};
  22156. return Effect;
  22157. })();
  22158. BABYLON.Effect = Effect;
  22159. })(BABYLON || (BABYLON = {}));
  22160. var BABYLON;
  22161. (function (BABYLON) {
  22162. var MaterialHelper = (function () {
  22163. function MaterialHelper() {
  22164. }
  22165. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  22166. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22167. var lightIndex = 0;
  22168. var needNormals = false;
  22169. var needRebuild = false;
  22170. for (var index = 0; index < scene.lights.length; index++) {
  22171. var light = scene.lights[index];
  22172. if (!light.isEnabled()) {
  22173. continue;
  22174. }
  22175. // Excluded check
  22176. if (light._excludedMeshesIds.length > 0) {
  22177. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  22178. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  22179. if (excludedMesh) {
  22180. light.excludedMeshes.push(excludedMesh);
  22181. }
  22182. }
  22183. light._excludedMeshesIds = [];
  22184. }
  22185. // Included check
  22186. if (light._includedOnlyMeshesIds.length > 0) {
  22187. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  22188. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22189. if (includedOnlyMesh) {
  22190. light.includedOnlyMeshes.push(includedOnlyMesh);
  22191. }
  22192. }
  22193. light._includedOnlyMeshesIds = [];
  22194. }
  22195. if (!light.canAffectMesh(mesh)) {
  22196. continue;
  22197. }
  22198. needNormals = true;
  22199. if (defines["LIGHT" + lightIndex] === undefined) {
  22200. needRebuild = true;
  22201. }
  22202. defines["LIGHT" + lightIndex] = true;
  22203. var type;
  22204. if (light instanceof BABYLON.SpotLight) {
  22205. type = "SPOTLIGHT" + lightIndex;
  22206. }
  22207. else if (light instanceof BABYLON.HemisphericLight) {
  22208. type = "HEMILIGHT" + lightIndex;
  22209. }
  22210. else if (light instanceof BABYLON.PointLight) {
  22211. type = "POINTLIGHT" + lightIndex;
  22212. }
  22213. else {
  22214. type = "DIRLIGHT" + lightIndex;
  22215. }
  22216. if (defines[type] === undefined) {
  22217. needRebuild = true;
  22218. }
  22219. defines[type] = true;
  22220. // Specular
  22221. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22222. defines["SPECULARTERM"] = true;
  22223. }
  22224. // Shadows
  22225. if (scene.shadowsEnabled) {
  22226. var shadowGenerator = light.getShadowGenerator();
  22227. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22228. if (defines["SHADOW" + lightIndex] === undefined) {
  22229. needRebuild = true;
  22230. }
  22231. defines["SHADOW" + lightIndex] = true;
  22232. defines["SHADOWS"] = true;
  22233. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22234. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  22235. needRebuild = true;
  22236. }
  22237. defines["SHADOWVSM" + lightIndex] = true;
  22238. }
  22239. if (shadowGenerator.usePoissonSampling) {
  22240. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  22241. needRebuild = true;
  22242. }
  22243. defines["SHADOWPCF" + lightIndex] = true;
  22244. }
  22245. }
  22246. }
  22247. lightIndex++;
  22248. if (lightIndex === maxSimultaneousLights)
  22249. break;
  22250. }
  22251. if (needRebuild) {
  22252. defines.rebuild();
  22253. }
  22254. return needNormals;
  22255. };
  22256. MaterialHelper.PrepareUniformsListForList = function (uniformsList, defines, maxSimultaneousLights) {
  22257. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22258. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22259. if (!defines["LIGHT" + lightIndex]) {
  22260. break;
  22261. }
  22262. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22263. }
  22264. };
  22265. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22266. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22267. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22268. if (!defines["LIGHT" + lightIndex]) {
  22269. break;
  22270. }
  22271. if (lightIndex > 0) {
  22272. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22273. }
  22274. if (defines["SHADOW" + lightIndex]) {
  22275. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22276. }
  22277. if (defines["SHADOWPCF" + lightIndex]) {
  22278. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22279. }
  22280. if (defines["SHADOWVSM" + lightIndex]) {
  22281. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22282. }
  22283. }
  22284. };
  22285. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22286. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22287. fallbacks.addCPUSkinningFallback(0, mesh);
  22288. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22289. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22290. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22291. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22292. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22293. }
  22294. }
  22295. };
  22296. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22297. if (defines["INSTANCES"]) {
  22298. attribs.push("world0");
  22299. attribs.push("world1");
  22300. attribs.push("world2");
  22301. attribs.push("world3");
  22302. }
  22303. };
  22304. // Bindings
  22305. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22306. var shadowGenerator = light.getShadowGenerator();
  22307. if (mesh.receiveShadows && shadowGenerator) {
  22308. if (!light.needCube()) {
  22309. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22310. }
  22311. else {
  22312. if (!depthValuesAlreadySet) {
  22313. depthValuesAlreadySet = true;
  22314. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22315. }
  22316. }
  22317. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22318. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22319. }
  22320. return depthValuesAlreadySet;
  22321. };
  22322. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22323. if (light instanceof BABYLON.PointLight) {
  22324. // Point Light
  22325. light.transferToEffect(effect, "vLightData" + lightIndex);
  22326. }
  22327. else if (light instanceof BABYLON.DirectionalLight) {
  22328. // Directional Light
  22329. light.transferToEffect(effect, "vLightData" + lightIndex);
  22330. }
  22331. else if (light instanceof BABYLON.SpotLight) {
  22332. // Spot Light
  22333. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22334. }
  22335. else if (light instanceof BABYLON.HemisphericLight) {
  22336. // Hemispheric Light
  22337. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22338. }
  22339. };
  22340. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22341. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22342. var lightIndex = 0;
  22343. var depthValuesAlreadySet = false;
  22344. for (var index = 0; index < scene.lights.length; index++) {
  22345. var light = scene.lights[index];
  22346. if (!light.isEnabled()) {
  22347. continue;
  22348. }
  22349. if (!light.canAffectMesh(mesh)) {
  22350. continue;
  22351. }
  22352. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22353. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22354. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22355. if (defines["SPECULARTERM"]) {
  22356. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22357. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22358. }
  22359. // Shadows
  22360. if (scene.shadowsEnabled) {
  22361. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22362. }
  22363. lightIndex++;
  22364. if (lightIndex === maxSimultaneousLights)
  22365. break;
  22366. }
  22367. };
  22368. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22369. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22370. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22371. effect.setColor3("vFogColor", scene.fogColor);
  22372. }
  22373. };
  22374. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22375. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22376. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22377. }
  22378. };
  22379. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22380. if (defines["LOGARITHMICDEPTH"]) {
  22381. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22382. }
  22383. };
  22384. MaterialHelper.BindClipPlane = function (effect, scene) {
  22385. if (scene.clipPlane) {
  22386. var clipPlane = scene.clipPlane;
  22387. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22388. }
  22389. };
  22390. return MaterialHelper;
  22391. })();
  22392. BABYLON.MaterialHelper = MaterialHelper;
  22393. })(BABYLON || (BABYLON = {}));
  22394. var BABYLON;
  22395. (function (BABYLON) {
  22396. var FresnelParameters = (function () {
  22397. function FresnelParameters() {
  22398. this.isEnabled = true;
  22399. this.leftColor = BABYLON.Color3.White();
  22400. this.rightColor = BABYLON.Color3.Black();
  22401. this.bias = 0;
  22402. this.power = 1;
  22403. }
  22404. FresnelParameters.prototype.clone = function () {
  22405. var newFresnelParameters = new FresnelParameters();
  22406. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22407. return new FresnelParameters;
  22408. };
  22409. FresnelParameters.prototype.serialize = function () {
  22410. var serializationObject = {};
  22411. serializationObject.isEnabled = this.isEnabled;
  22412. serializationObject.leftColor = this.leftColor;
  22413. serializationObject.rightColor = this.rightColor;
  22414. serializationObject.bias = this.bias;
  22415. serializationObject.power = this.power;
  22416. return serializationObject;
  22417. };
  22418. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22419. var fresnelParameters = new FresnelParameters();
  22420. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22421. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22422. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22423. fresnelParameters.bias = parsedFresnelParameters.bias;
  22424. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22425. return fresnelParameters;
  22426. };
  22427. return FresnelParameters;
  22428. })();
  22429. BABYLON.FresnelParameters = FresnelParameters;
  22430. })(BABYLON || (BABYLON = {}));
  22431. var BABYLON;
  22432. (function (BABYLON) {
  22433. var MaterialDefines = (function () {
  22434. function MaterialDefines() {
  22435. }
  22436. MaterialDefines.prototype.rebuild = function () {
  22437. if (this._keys) {
  22438. delete this._keys;
  22439. }
  22440. this._keys = Object.keys(this);
  22441. };
  22442. MaterialDefines.prototype.isEqual = function (other) {
  22443. if (this._keys.length !== other._keys.length) {
  22444. return false;
  22445. }
  22446. for (var index = 0; index < this._keys.length; index++) {
  22447. var prop = this._keys[index];
  22448. if (this[prop] !== other[prop]) {
  22449. return false;
  22450. }
  22451. }
  22452. return true;
  22453. };
  22454. MaterialDefines.prototype.cloneTo = function (other) {
  22455. if (this._keys.length !== other._keys.length) {
  22456. other._keys = this._keys.slice(0);
  22457. }
  22458. for (var index = 0; index < this._keys.length; index++) {
  22459. var prop = this._keys[index];
  22460. other[prop] = this[prop];
  22461. }
  22462. };
  22463. MaterialDefines.prototype.reset = function () {
  22464. for (var index = 0; index < this._keys.length; index++) {
  22465. var prop = this._keys[index];
  22466. if (typeof (this[prop]) === "number") {
  22467. this[prop] = 0;
  22468. }
  22469. else {
  22470. this[prop] = false;
  22471. }
  22472. }
  22473. };
  22474. MaterialDefines.prototype.toString = function () {
  22475. var result = "";
  22476. for (var index = 0; index < this._keys.length; index++) {
  22477. var prop = this._keys[index];
  22478. if (typeof (this[prop]) === "number") {
  22479. result += "#define " + prop + " " + this[prop] + "\n";
  22480. }
  22481. else if (this[prop]) {
  22482. result += "#define " + prop + "\n";
  22483. }
  22484. }
  22485. return result;
  22486. };
  22487. return MaterialDefines;
  22488. })();
  22489. BABYLON.MaterialDefines = MaterialDefines;
  22490. var Material = (function () {
  22491. function Material(name, scene, doNotAdd) {
  22492. this.name = name;
  22493. this.checkReadyOnEveryCall = false;
  22494. this.checkReadyOnlyOnce = false;
  22495. this.state = "";
  22496. this.alpha = 1.0;
  22497. this.backFaceCulling = true;
  22498. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22499. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22500. this.disableDepthWrite = false;
  22501. this.fogEnabled = true;
  22502. this.pointSize = 1.0;
  22503. this.zOffset = 0;
  22504. this._wasPreviouslyReady = false;
  22505. this._fillMode = Material.TriangleFillMode;
  22506. this.id = name;
  22507. this._scene = scene;
  22508. if (!doNotAdd) {
  22509. scene.materials.push(this);
  22510. }
  22511. }
  22512. Object.defineProperty(Material, "TriangleFillMode", {
  22513. get: function () {
  22514. return Material._TriangleFillMode;
  22515. },
  22516. enumerable: true,
  22517. configurable: true
  22518. });
  22519. Object.defineProperty(Material, "WireFrameFillMode", {
  22520. get: function () {
  22521. return Material._WireFrameFillMode;
  22522. },
  22523. enumerable: true,
  22524. configurable: true
  22525. });
  22526. Object.defineProperty(Material, "PointFillMode", {
  22527. get: function () {
  22528. return Material._PointFillMode;
  22529. },
  22530. enumerable: true,
  22531. configurable: true
  22532. });
  22533. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22534. get: function () {
  22535. return Material._ClockWiseSideOrientation;
  22536. },
  22537. enumerable: true,
  22538. configurable: true
  22539. });
  22540. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22541. get: function () {
  22542. return Material._CounterClockWiseSideOrientation;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. Object.defineProperty(Material.prototype, "wireframe", {
  22548. get: function () {
  22549. return this._fillMode === Material.WireFrameFillMode;
  22550. },
  22551. set: function (value) {
  22552. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. Object.defineProperty(Material.prototype, "pointsCloud", {
  22558. get: function () {
  22559. return this._fillMode === Material.PointFillMode;
  22560. },
  22561. set: function (value) {
  22562. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(Material.prototype, "fillMode", {
  22568. get: function () {
  22569. return this._fillMode;
  22570. },
  22571. set: function (value) {
  22572. this._fillMode = value;
  22573. },
  22574. enumerable: true,
  22575. configurable: true
  22576. });
  22577. /**
  22578. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22579. * subclasses should override adding information pertainent to themselves
  22580. */
  22581. Material.prototype.toString = function (fullDetails) {
  22582. var ret = "Name: " + this.name;
  22583. if (fullDetails) {
  22584. }
  22585. return ret;
  22586. };
  22587. Object.defineProperty(Material.prototype, "isFrozen", {
  22588. get: function () {
  22589. return this.checkReadyOnlyOnce;
  22590. },
  22591. enumerable: true,
  22592. configurable: true
  22593. });
  22594. Material.prototype.freeze = function () {
  22595. this.checkReadyOnlyOnce = true;
  22596. };
  22597. Material.prototype.unfreeze = function () {
  22598. this.checkReadyOnlyOnce = false;
  22599. };
  22600. Material.prototype.isReady = function (mesh, useInstances) {
  22601. return true;
  22602. };
  22603. Material.prototype.getEffect = function () {
  22604. return this._effect;
  22605. };
  22606. Material.prototype.getScene = function () {
  22607. return this._scene;
  22608. };
  22609. Material.prototype.needAlphaBlending = function () {
  22610. return (this.alpha < 1.0);
  22611. };
  22612. Material.prototype.needAlphaTesting = function () {
  22613. return false;
  22614. };
  22615. Material.prototype.getAlphaTestTexture = function () {
  22616. return null;
  22617. };
  22618. Material.prototype.trackCreation = function (onCompiled, onError) {
  22619. };
  22620. Material.prototype.markDirty = function () {
  22621. this._wasPreviouslyReady = false;
  22622. };
  22623. Material.prototype._preBind = function () {
  22624. var engine = this._scene.getEngine();
  22625. engine.enableEffect(this._effect);
  22626. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22627. };
  22628. Material.prototype.bind = function (world, mesh) {
  22629. this._scene._cachedMaterial = this;
  22630. if (this.onBind) {
  22631. this.onBind(this, mesh);
  22632. }
  22633. if (this.disableDepthWrite) {
  22634. var engine = this._scene.getEngine();
  22635. this._cachedDepthWriteState = engine.getDepthWrite();
  22636. engine.setDepthWrite(false);
  22637. }
  22638. };
  22639. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22640. };
  22641. Material.prototype.unbind = function () {
  22642. if (this.disableDepthWrite) {
  22643. var engine = this._scene.getEngine();
  22644. engine.setDepthWrite(this._cachedDepthWriteState);
  22645. }
  22646. };
  22647. Material.prototype.clone = function (name) {
  22648. return null;
  22649. };
  22650. Material.prototype.getBindedMeshes = function () {
  22651. var result = new Array();
  22652. for (var index = 0; index < this._scene.meshes.length; index++) {
  22653. var mesh = this._scene.meshes[index];
  22654. if (mesh.material === this) {
  22655. result.push(mesh);
  22656. }
  22657. }
  22658. return result;
  22659. };
  22660. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22661. // Animations
  22662. this.getScene().stopAnimation(this);
  22663. // Remove from scene
  22664. var index = this._scene.materials.indexOf(this);
  22665. if (index >= 0) {
  22666. this._scene.materials.splice(index, 1);
  22667. }
  22668. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22669. if (forceDisposeEffect && this._effect) {
  22670. this._scene.getEngine()._releaseEffect(this._effect);
  22671. this._effect = null;
  22672. }
  22673. // Remove from meshes
  22674. for (index = 0; index < this._scene.meshes.length; index++) {
  22675. var mesh = this._scene.meshes[index];
  22676. if (mesh.material === this) {
  22677. mesh.material = null;
  22678. }
  22679. }
  22680. // Callback
  22681. if (this.onDispose) {
  22682. this.onDispose();
  22683. }
  22684. };
  22685. Material.prototype.serialize = function () {
  22686. return BABYLON.SerializationHelper.Serialize(this);
  22687. };
  22688. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22689. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22690. multiMaterial.id = parsedMultiMaterial.id;
  22691. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22692. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22693. var subMatId = parsedMultiMaterial.materials[matIndex];
  22694. if (subMatId) {
  22695. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22696. }
  22697. else {
  22698. multiMaterial.subMaterials.push(null);
  22699. }
  22700. }
  22701. return multiMaterial;
  22702. };
  22703. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22704. if (!parsedMaterial.customType) {
  22705. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22706. }
  22707. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22708. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22709. ;
  22710. };
  22711. Material._TriangleFillMode = 0;
  22712. Material._WireFrameFillMode = 1;
  22713. Material._PointFillMode = 2;
  22714. Material._ClockWiseSideOrientation = 0;
  22715. Material._CounterClockWiseSideOrientation = 1;
  22716. __decorate([
  22717. BABYLON.serialize()
  22718. ], Material.prototype, "id", void 0);
  22719. __decorate([
  22720. BABYLON.serialize()
  22721. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22722. __decorate([
  22723. BABYLON.serialize()
  22724. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22725. __decorate([
  22726. BABYLON.serialize()
  22727. ], Material.prototype, "state", void 0);
  22728. __decorate([
  22729. BABYLON.serialize()
  22730. ], Material.prototype, "alpha", void 0);
  22731. __decorate([
  22732. BABYLON.serialize()
  22733. ], Material.prototype, "backFaceCulling", void 0);
  22734. __decorate([
  22735. BABYLON.serialize()
  22736. ], Material.prototype, "sideOrientation", void 0);
  22737. __decorate([
  22738. BABYLON.serialize()
  22739. ], Material.prototype, "alphaMode", void 0);
  22740. __decorate([
  22741. BABYLON.serialize()
  22742. ], Material.prototype, "disableDepthWrite", void 0);
  22743. __decorate([
  22744. BABYLON.serialize()
  22745. ], Material.prototype, "fogEnabled", void 0);
  22746. __decorate([
  22747. BABYLON.serialize()
  22748. ], Material.prototype, "pointSize", void 0);
  22749. __decorate([
  22750. BABYLON.serialize()
  22751. ], Material.prototype, "zOffset", void 0);
  22752. __decorate([
  22753. BABYLON.serialize()
  22754. ], Material.prototype, "wireframe", null);
  22755. __decorate([
  22756. BABYLON.serialize()
  22757. ], Material.prototype, "pointsCloud", null);
  22758. __decorate([
  22759. BABYLON.serialize()
  22760. ], Material.prototype, "fillMode", null);
  22761. return Material;
  22762. })();
  22763. BABYLON.Material = Material;
  22764. })(BABYLON || (BABYLON = {}));
  22765. var BABYLON;
  22766. (function (BABYLON) {
  22767. var StandardMaterialDefines = (function (_super) {
  22768. __extends(StandardMaterialDefines, _super);
  22769. function StandardMaterialDefines() {
  22770. _super.call(this);
  22771. this.DIFFUSE = false;
  22772. this.AMBIENT = false;
  22773. this.OPACITY = false;
  22774. this.OPACITYRGB = false;
  22775. this.REFLECTION = false;
  22776. this.EMISSIVE = false;
  22777. this.SPECULAR = false;
  22778. this.BUMP = false;
  22779. this.PARALLAX = false;
  22780. this.PARALLAXOCCLUSION = false;
  22781. this.SPECULAROVERALPHA = false;
  22782. this.CLIPPLANE = false;
  22783. this.ALPHATEST = false;
  22784. this.ALPHAFROMDIFFUSE = false;
  22785. this.POINTSIZE = false;
  22786. this.FOG = false;
  22787. this.SPECULARTERM = false;
  22788. this.DIFFUSEFRESNEL = false;
  22789. this.OPACITYFRESNEL = false;
  22790. this.REFLECTIONFRESNEL = false;
  22791. this.REFRACTIONFRESNEL = false;
  22792. this.EMISSIVEFRESNEL = false;
  22793. this.FRESNEL = false;
  22794. this.NORMAL = false;
  22795. this.UV1 = false;
  22796. this.UV2 = false;
  22797. this.VERTEXCOLOR = false;
  22798. this.VERTEXALPHA = false;
  22799. this.NUM_BONE_INFLUENCERS = 0;
  22800. this.BonesPerMesh = 0;
  22801. this.INSTANCES = false;
  22802. this.GLOSSINESS = false;
  22803. this.ROUGHNESS = false;
  22804. this.EMISSIVEASILLUMINATION = false;
  22805. this.LINKEMISSIVEWITHDIFFUSE = false;
  22806. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22807. this.LIGHTMAP = false;
  22808. this.USELIGHTMAPASSHADOWMAP = false;
  22809. this.REFLECTIONMAP_3D = false;
  22810. this.REFLECTIONMAP_SPHERICAL = false;
  22811. this.REFLECTIONMAP_PLANAR = false;
  22812. this.REFLECTIONMAP_CUBIC = false;
  22813. this.REFLECTIONMAP_PROJECTION = false;
  22814. this.REFLECTIONMAP_SKYBOX = false;
  22815. this.REFLECTIONMAP_EXPLICIT = false;
  22816. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22817. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22818. this.INVERTCUBICMAP = false;
  22819. this.LOGARITHMICDEPTH = false;
  22820. this.REFRACTION = false;
  22821. this.REFRACTIONMAP_3D = false;
  22822. this.REFLECTIONOVERALPHA = false;
  22823. this.rebuild();
  22824. }
  22825. return StandardMaterialDefines;
  22826. })(BABYLON.MaterialDefines);
  22827. var StandardMaterial = (function (_super) {
  22828. __extends(StandardMaterial, _super);
  22829. function StandardMaterial(name, scene) {
  22830. var _this = this;
  22831. _super.call(this, name, scene);
  22832. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22833. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22834. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22835. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22836. this.specularPower = 64;
  22837. this.useAlphaFromDiffuseTexture = false;
  22838. this.useEmissiveAsIllumination = false;
  22839. this.linkEmissiveWithDiffuse = false;
  22840. this.useReflectionFresnelFromSpecular = false;
  22841. this.useSpecularOverAlpha = false;
  22842. this.useReflectionOverAlpha = false;
  22843. this.disableLighting = false;
  22844. this.useParallax = false;
  22845. this.useParallaxOcclusion = false;
  22846. this.parallaxScaleBias = 0.05;
  22847. this.roughness = 0;
  22848. this.indexOfRefraction = 0.98;
  22849. this.invertRefractionY = true;
  22850. this.useLightmapAsShadowmap = false;
  22851. this.useGlossinessFromSpecularMapAlpha = false;
  22852. this.maxSimultaneousLights = 4;
  22853. this._renderTargets = new BABYLON.SmartArray(16);
  22854. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22855. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22856. this._defines = new StandardMaterialDefines();
  22857. this._cachedDefines = new StandardMaterialDefines();
  22858. this._cachedDefines.BonesPerMesh = -1;
  22859. this.getRenderTargetTextures = function () {
  22860. _this._renderTargets.reset();
  22861. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22862. _this._renderTargets.push(_this.reflectionTexture);
  22863. }
  22864. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22865. _this._renderTargets.push(_this.refractionTexture);
  22866. }
  22867. return _this._renderTargets;
  22868. };
  22869. }
  22870. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22871. get: function () {
  22872. return this._useLogarithmicDepth;
  22873. },
  22874. set: function (value) {
  22875. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22876. },
  22877. enumerable: true,
  22878. configurable: true
  22879. });
  22880. StandardMaterial.prototype.needAlphaBlending = function () {
  22881. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22882. };
  22883. StandardMaterial.prototype.needAlphaTesting = function () {
  22884. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22885. };
  22886. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22887. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22888. };
  22889. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22890. return this.diffuseTexture;
  22891. };
  22892. // Methods
  22893. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22894. if (!mesh) {
  22895. return true;
  22896. }
  22897. if (this._defines.INSTANCES !== useInstances) {
  22898. return false;
  22899. }
  22900. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22901. return true;
  22902. }
  22903. return false;
  22904. };
  22905. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22906. if (this.isFrozen) {
  22907. if (this._wasPreviouslyReady) {
  22908. return true;
  22909. }
  22910. }
  22911. var scene = this.getScene();
  22912. if (!this.checkReadyOnEveryCall) {
  22913. if (this._renderId === scene.getRenderId()) {
  22914. if (this._checkCache(scene, mesh, useInstances)) {
  22915. return true;
  22916. }
  22917. }
  22918. }
  22919. var engine = scene.getEngine();
  22920. var needNormals = false;
  22921. var needUVs = false;
  22922. this._defines.reset();
  22923. // Textures
  22924. if (scene.texturesEnabled) {
  22925. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22926. if (!this.diffuseTexture.isReady()) {
  22927. return false;
  22928. }
  22929. else {
  22930. needUVs = true;
  22931. this._defines.DIFFUSE = true;
  22932. }
  22933. }
  22934. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22935. if (!this.ambientTexture.isReady()) {
  22936. return false;
  22937. }
  22938. else {
  22939. needUVs = true;
  22940. this._defines.AMBIENT = true;
  22941. }
  22942. }
  22943. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22944. if (!this.opacityTexture.isReady()) {
  22945. return false;
  22946. }
  22947. else {
  22948. needUVs = true;
  22949. this._defines.OPACITY = true;
  22950. if (this.opacityTexture.getAlphaFromRGB) {
  22951. this._defines.OPACITYRGB = true;
  22952. }
  22953. }
  22954. }
  22955. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22956. if (!this.reflectionTexture.isReady()) {
  22957. return false;
  22958. }
  22959. else {
  22960. needNormals = true;
  22961. this._defines.REFLECTION = true;
  22962. if (this.roughness > 0) {
  22963. this._defines.ROUGHNESS = true;
  22964. }
  22965. if (this.useReflectionOverAlpha) {
  22966. this._defines.REFLECTIONOVERALPHA = true;
  22967. }
  22968. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22969. this._defines.INVERTCUBICMAP = true;
  22970. }
  22971. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22972. switch (this.reflectionTexture.coordinatesMode) {
  22973. case BABYLON.Texture.CUBIC_MODE:
  22974. case BABYLON.Texture.INVCUBIC_MODE:
  22975. this._defines.REFLECTIONMAP_CUBIC = true;
  22976. break;
  22977. case BABYLON.Texture.EXPLICIT_MODE:
  22978. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22979. break;
  22980. case BABYLON.Texture.PLANAR_MODE:
  22981. this._defines.REFLECTIONMAP_PLANAR = true;
  22982. break;
  22983. case BABYLON.Texture.PROJECTION_MODE:
  22984. this._defines.REFLECTIONMAP_PROJECTION = true;
  22985. break;
  22986. case BABYLON.Texture.SKYBOX_MODE:
  22987. this._defines.REFLECTIONMAP_SKYBOX = true;
  22988. break;
  22989. case BABYLON.Texture.SPHERICAL_MODE:
  22990. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22991. break;
  22992. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22993. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22994. break;
  22995. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22996. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22997. break;
  22998. }
  22999. }
  23000. }
  23001. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23002. if (!this.emissiveTexture.isReady()) {
  23003. return false;
  23004. }
  23005. else {
  23006. needUVs = true;
  23007. this._defines.EMISSIVE = true;
  23008. }
  23009. }
  23010. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23011. if (!this.lightmapTexture.isReady()) {
  23012. return false;
  23013. }
  23014. else {
  23015. needUVs = true;
  23016. this._defines.LIGHTMAP = true;
  23017. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  23018. }
  23019. }
  23020. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23021. if (!this.specularTexture.isReady()) {
  23022. return false;
  23023. }
  23024. else {
  23025. needUVs = true;
  23026. this._defines.SPECULAR = true;
  23027. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  23028. }
  23029. }
  23030. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  23031. if (!this.bumpTexture.isReady()) {
  23032. return false;
  23033. }
  23034. else {
  23035. needUVs = true;
  23036. this._defines.BUMP = true;
  23037. if (this.useParallax) {
  23038. this._defines.PARALLAX = true;
  23039. if (this.useParallaxOcclusion) {
  23040. this._defines.PARALLAXOCCLUSION = true;
  23041. }
  23042. }
  23043. }
  23044. }
  23045. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23046. if (!this.refractionTexture.isReady()) {
  23047. return false;
  23048. }
  23049. else {
  23050. needUVs = true;
  23051. this._defines.REFRACTION = true;
  23052. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  23053. }
  23054. }
  23055. }
  23056. // Effect
  23057. if (scene.clipPlane) {
  23058. this._defines.CLIPPLANE = true;
  23059. }
  23060. if (engine.getAlphaTesting()) {
  23061. this._defines.ALPHATEST = true;
  23062. }
  23063. if (this._shouldUseAlphaFromDiffuseTexture()) {
  23064. this._defines.ALPHAFROMDIFFUSE = true;
  23065. }
  23066. if (this.useEmissiveAsIllumination) {
  23067. this._defines.EMISSIVEASILLUMINATION = true;
  23068. }
  23069. if (this.linkEmissiveWithDiffuse) {
  23070. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  23071. }
  23072. if (this.useLogarithmicDepth) {
  23073. this._defines.LOGARITHMICDEPTH = true;
  23074. }
  23075. // Point size
  23076. if (this.pointsCloud || scene.forcePointsCloud) {
  23077. this._defines.POINTSIZE = true;
  23078. }
  23079. // Fog
  23080. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  23081. this._defines.FOG = true;
  23082. }
  23083. if (scene.lightsEnabled && !this.disableLighting) {
  23084. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  23085. }
  23086. if (StandardMaterial.FresnelEnabled) {
  23087. // Fresnel
  23088. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  23089. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  23090. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  23091. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  23092. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23093. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23094. this._defines.DIFFUSEFRESNEL = true;
  23095. }
  23096. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23097. this._defines.OPACITYFRESNEL = true;
  23098. }
  23099. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23100. this._defines.REFLECTIONFRESNEL = true;
  23101. if (this.useReflectionFresnelFromSpecular) {
  23102. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  23103. }
  23104. }
  23105. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23106. this._defines.REFRACTIONFRESNEL = true;
  23107. }
  23108. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23109. this._defines.EMISSIVEFRESNEL = true;
  23110. }
  23111. needNormals = true;
  23112. this._defines.FRESNEL = true;
  23113. }
  23114. }
  23115. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  23116. this._defines.SPECULAROVERALPHA = true;
  23117. }
  23118. // Attribs
  23119. if (mesh) {
  23120. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23121. this._defines.NORMAL = true;
  23122. }
  23123. if (needUVs) {
  23124. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23125. this._defines.UV1 = true;
  23126. }
  23127. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23128. this._defines.UV2 = true;
  23129. }
  23130. }
  23131. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23132. this._defines.VERTEXCOLOR = true;
  23133. if (mesh.hasVertexAlpha) {
  23134. this._defines.VERTEXALPHA = true;
  23135. }
  23136. }
  23137. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23138. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  23139. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  23140. }
  23141. // Instances
  23142. if (useInstances) {
  23143. this._defines.INSTANCES = true;
  23144. }
  23145. }
  23146. // Get correct effect
  23147. if (!this._defines.isEqual(this._cachedDefines)) {
  23148. this._defines.cloneTo(this._cachedDefines);
  23149. scene.resetCachedMaterial();
  23150. // Fallbacks
  23151. var fallbacks = new BABYLON.EffectFallbacks();
  23152. if (this._defines.REFLECTION) {
  23153. fallbacks.addFallback(0, "REFLECTION");
  23154. }
  23155. if (this._defines.SPECULAR) {
  23156. fallbacks.addFallback(0, "SPECULAR");
  23157. }
  23158. if (this._defines.BUMP) {
  23159. fallbacks.addFallback(0, "BUMP");
  23160. }
  23161. if (this._defines.PARALLAX) {
  23162. fallbacks.addFallback(1, "PARALLAX");
  23163. }
  23164. if (this._defines.PARALLAXOCCLUSION) {
  23165. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  23166. }
  23167. if (this._defines.SPECULAROVERALPHA) {
  23168. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  23169. }
  23170. if (this._defines.FOG) {
  23171. fallbacks.addFallback(1, "FOG");
  23172. }
  23173. if (this._defines.POINTSIZE) {
  23174. fallbacks.addFallback(0, "POINTSIZE");
  23175. }
  23176. if (this._defines.LOGARITHMICDEPTH) {
  23177. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  23178. }
  23179. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  23180. if (this._defines.SPECULARTERM) {
  23181. fallbacks.addFallback(0, "SPECULARTERM");
  23182. }
  23183. if (this._defines.DIFFUSEFRESNEL) {
  23184. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  23185. }
  23186. if (this._defines.OPACITYFRESNEL) {
  23187. fallbacks.addFallback(2, "OPACITYFRESNEL");
  23188. }
  23189. if (this._defines.REFLECTIONFRESNEL) {
  23190. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  23191. }
  23192. if (this._defines.EMISSIVEFRESNEL) {
  23193. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  23194. }
  23195. if (this._defines.FRESNEL) {
  23196. fallbacks.addFallback(4, "FRESNEL");
  23197. }
  23198. //Attributes
  23199. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23200. if (this._defines.NORMAL) {
  23201. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23202. }
  23203. if (this._defines.UV1) {
  23204. attribs.push(BABYLON.VertexBuffer.UVKind);
  23205. }
  23206. if (this._defines.UV2) {
  23207. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23208. }
  23209. if (this._defines.VERTEXCOLOR) {
  23210. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23211. }
  23212. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23213. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23214. // Legacy browser patch
  23215. var shaderName = "default";
  23216. if (!scene.getEngine().getCaps().standardDerivatives) {
  23217. shaderName = "legacydefault";
  23218. }
  23219. var join = this._defines.toString();
  23220. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23221. "vFogInfos", "vFogColor", "pointSize",
  23222. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23223. "mBones",
  23224. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23225. "depthValues",
  23226. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23227. "logarithmicDepthConstant"
  23228. ];
  23229. BABYLON.MaterialHelper.PrepareUniformsListForList(uniforms, this._defines, this.maxSimultaneousLights);
  23230. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  23231. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  23232. ], join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  23233. }
  23234. if (!this._effect.isReady()) {
  23235. return false;
  23236. }
  23237. this._renderId = scene.getRenderId();
  23238. this._wasPreviouslyReady = true;
  23239. if (mesh) {
  23240. if (!mesh._materialDefines) {
  23241. mesh._materialDefines = new StandardMaterialDefines();
  23242. }
  23243. this._defines.cloneTo(mesh._materialDefines);
  23244. }
  23245. return true;
  23246. };
  23247. StandardMaterial.prototype.unbind = function () {
  23248. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23249. this._effect.setTexture("reflection2DSampler", null);
  23250. }
  23251. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23252. this._effect.setTexture("refraction2DSampler", null);
  23253. }
  23254. _super.prototype.unbind.call(this);
  23255. };
  23256. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23257. this._effect.setMatrix("world", world);
  23258. };
  23259. StandardMaterial.prototype.bind = function (world, mesh) {
  23260. var scene = this.getScene();
  23261. // Matrices
  23262. this.bindOnlyWorldMatrix(world);
  23263. // Bones
  23264. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23265. if (scene.getCachedMaterial() !== this) {
  23266. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23267. if (StandardMaterial.FresnelEnabled) {
  23268. // Fresnel
  23269. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23270. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23271. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23272. }
  23273. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23274. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23275. }
  23276. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23277. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23278. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23279. }
  23280. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23281. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23282. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23283. }
  23284. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23285. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23286. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23287. }
  23288. }
  23289. // Textures
  23290. if (scene.texturesEnabled) {
  23291. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23292. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23293. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23294. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23295. }
  23296. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23297. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23298. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23299. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23300. }
  23301. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23302. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23303. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23304. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23305. }
  23306. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23307. if (this.reflectionTexture.isCube) {
  23308. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23309. }
  23310. else {
  23311. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23312. }
  23313. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23314. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23315. }
  23316. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23317. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23318. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23319. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23320. }
  23321. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23322. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23323. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23324. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23325. }
  23326. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23327. this._effect.setTexture("specularSampler", this.specularTexture);
  23328. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23329. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23330. }
  23331. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23332. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23333. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23334. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23335. }
  23336. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23337. var depth = 1.0;
  23338. if (this.refractionTexture.isCube) {
  23339. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23340. }
  23341. else {
  23342. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23343. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23344. if (this.refractionTexture.depth) {
  23345. depth = this.refractionTexture.depth;
  23346. }
  23347. }
  23348. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23349. }
  23350. }
  23351. // Clip plane
  23352. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23353. // Point size
  23354. if (this.pointsCloud) {
  23355. this._effect.setFloat("pointSize", this.pointSize);
  23356. }
  23357. // Colors
  23358. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23359. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23360. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23361. if (this._defines.SPECULARTERM) {
  23362. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23363. }
  23364. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23365. }
  23366. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23367. // Diffuse
  23368. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23369. // Lights
  23370. if (scene.lightsEnabled && !this.disableLighting) {
  23371. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  23372. }
  23373. // View
  23374. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23375. this._effect.setMatrix("view", scene.getViewMatrix());
  23376. }
  23377. // Fog
  23378. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23379. // Log. depth
  23380. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23381. }
  23382. _super.prototype.bind.call(this, world, mesh);
  23383. };
  23384. StandardMaterial.prototype.getAnimatables = function () {
  23385. var results = [];
  23386. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23387. results.push(this.diffuseTexture);
  23388. }
  23389. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23390. results.push(this.ambientTexture);
  23391. }
  23392. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23393. results.push(this.opacityTexture);
  23394. }
  23395. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23396. results.push(this.reflectionTexture);
  23397. }
  23398. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23399. results.push(this.emissiveTexture);
  23400. }
  23401. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23402. results.push(this.specularTexture);
  23403. }
  23404. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23405. results.push(this.bumpTexture);
  23406. }
  23407. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23408. results.push(this.lightmapTexture);
  23409. }
  23410. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23411. results.push(this.refractionTexture);
  23412. }
  23413. return results;
  23414. };
  23415. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23416. if (forceDisposeTextures) {
  23417. if (this.diffuseTexture) {
  23418. this.diffuseTexture.dispose();
  23419. }
  23420. if (this.ambientTexture) {
  23421. this.ambientTexture.dispose();
  23422. }
  23423. if (this.opacityTexture) {
  23424. this.opacityTexture.dispose();
  23425. }
  23426. if (this.reflectionTexture) {
  23427. this.reflectionTexture.dispose();
  23428. }
  23429. if (this.emissiveTexture) {
  23430. this.emissiveTexture.dispose();
  23431. }
  23432. if (this.specularTexture) {
  23433. this.specularTexture.dispose();
  23434. }
  23435. if (this.bumpTexture) {
  23436. this.bumpTexture.dispose();
  23437. }
  23438. if (this.lightmapTexture) {
  23439. this.lightmapTexture.dispose();
  23440. }
  23441. if (this.refractionTexture) {
  23442. this.refractionTexture.dispose();
  23443. }
  23444. }
  23445. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  23446. };
  23447. StandardMaterial.prototype.clone = function (name) {
  23448. var _this = this;
  23449. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23450. };
  23451. StandardMaterial.prototype.serialize = function () {
  23452. return BABYLON.SerializationHelper.Serialize(this);
  23453. };
  23454. // Statics
  23455. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23456. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23457. };
  23458. // Flags used to enable or disable a type of texture for all Standard Materials
  23459. StandardMaterial.DiffuseTextureEnabled = true;
  23460. StandardMaterial.AmbientTextureEnabled = true;
  23461. StandardMaterial.OpacityTextureEnabled = true;
  23462. StandardMaterial.ReflectionTextureEnabled = true;
  23463. StandardMaterial.EmissiveTextureEnabled = true;
  23464. StandardMaterial.SpecularTextureEnabled = true;
  23465. StandardMaterial.BumpTextureEnabled = true;
  23466. StandardMaterial.FresnelEnabled = true;
  23467. StandardMaterial.LightmapTextureEnabled = true;
  23468. StandardMaterial.RefractionTextureEnabled = true;
  23469. __decorate([
  23470. BABYLON.serializeAsTexture()
  23471. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23472. __decorate([
  23473. BABYLON.serializeAsTexture()
  23474. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23475. __decorate([
  23476. BABYLON.serializeAsTexture()
  23477. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23478. __decorate([
  23479. BABYLON.serializeAsTexture()
  23480. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23481. __decorate([
  23482. BABYLON.serializeAsTexture()
  23483. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23484. __decorate([
  23485. BABYLON.serializeAsTexture()
  23486. ], StandardMaterial.prototype, "specularTexture", void 0);
  23487. __decorate([
  23488. BABYLON.serializeAsTexture()
  23489. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23490. __decorate([
  23491. BABYLON.serializeAsTexture()
  23492. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23493. __decorate([
  23494. BABYLON.serializeAsTexture()
  23495. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23496. __decorate([
  23497. BABYLON.serializeAsColor3("ambient")
  23498. ], StandardMaterial.prototype, "ambientColor", void 0);
  23499. __decorate([
  23500. BABYLON.serializeAsColor3("diffuse")
  23501. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23502. __decorate([
  23503. BABYLON.serializeAsColor3("specular")
  23504. ], StandardMaterial.prototype, "specularColor", void 0);
  23505. __decorate([
  23506. BABYLON.serializeAsColor3("emissive")
  23507. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23508. __decorate([
  23509. BABYLON.serialize()
  23510. ], StandardMaterial.prototype, "specularPower", void 0);
  23511. __decorate([
  23512. BABYLON.serialize()
  23513. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23514. __decorate([
  23515. BABYLON.serialize()
  23516. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23517. __decorate([
  23518. BABYLON.serialize()
  23519. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23520. __decorate([
  23521. BABYLON.serialize()
  23522. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23523. __decorate([
  23524. BABYLON.serialize()
  23525. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23526. __decorate([
  23527. BABYLON.serialize()
  23528. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23529. __decorate([
  23530. BABYLON.serialize()
  23531. ], StandardMaterial.prototype, "disableLighting", void 0);
  23532. __decorate([
  23533. BABYLON.serialize()
  23534. ], StandardMaterial.prototype, "useParallax", void 0);
  23535. __decorate([
  23536. BABYLON.serialize()
  23537. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23538. __decorate([
  23539. BABYLON.serialize()
  23540. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23541. __decorate([
  23542. BABYLON.serialize()
  23543. ], StandardMaterial.prototype, "roughness", void 0);
  23544. __decorate([
  23545. BABYLON.serialize()
  23546. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23547. __decorate([
  23548. BABYLON.serialize()
  23549. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23550. __decorate([
  23551. BABYLON.serialize()
  23552. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23553. __decorate([
  23554. BABYLON.serializeAsFresnelParameters()
  23555. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23556. __decorate([
  23557. BABYLON.serializeAsFresnelParameters()
  23558. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23559. __decorate([
  23560. BABYLON.serializeAsFresnelParameters()
  23561. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23562. __decorate([
  23563. BABYLON.serializeAsFresnelParameters()
  23564. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23565. __decorate([
  23566. BABYLON.serializeAsFresnelParameters()
  23567. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23568. __decorate([
  23569. BABYLON.serialize()
  23570. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23571. __decorate([
  23572. BABYLON.serialize()
  23573. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  23574. __decorate([
  23575. BABYLON.serialize()
  23576. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23577. return StandardMaterial;
  23578. })(BABYLON.Material);
  23579. BABYLON.StandardMaterial = StandardMaterial;
  23580. })(BABYLON || (BABYLON = {}));
  23581. var BABYLON;
  23582. (function (BABYLON) {
  23583. var MultiMaterial = (function (_super) {
  23584. __extends(MultiMaterial, _super);
  23585. function MultiMaterial(name, scene) {
  23586. _super.call(this, name, scene, true);
  23587. this.subMaterials = new Array();
  23588. scene.multiMaterials.push(this);
  23589. }
  23590. // Properties
  23591. MultiMaterial.prototype.getSubMaterial = function (index) {
  23592. if (index < 0 || index >= this.subMaterials.length) {
  23593. return this.getScene().defaultMaterial;
  23594. }
  23595. return this.subMaterials[index];
  23596. };
  23597. // Methods
  23598. MultiMaterial.prototype.isReady = function (mesh) {
  23599. for (var index = 0; index < this.subMaterials.length; index++) {
  23600. var subMaterial = this.subMaterials[index];
  23601. if (subMaterial) {
  23602. if (!this.subMaterials[index].isReady(mesh)) {
  23603. return false;
  23604. }
  23605. }
  23606. }
  23607. return true;
  23608. };
  23609. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23610. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23611. for (var index = 0; index < this.subMaterials.length; index++) {
  23612. var subMaterial = null;
  23613. if (cloneChildren) {
  23614. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23615. }
  23616. else {
  23617. subMaterial = this.subMaterials[index];
  23618. }
  23619. newMultiMaterial.subMaterials.push(subMaterial);
  23620. }
  23621. return newMultiMaterial;
  23622. };
  23623. MultiMaterial.prototype.serialize = function () {
  23624. var serializationObject = {};
  23625. serializationObject.name = this.name;
  23626. serializationObject.id = this.id;
  23627. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23628. serializationObject.materials = [];
  23629. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23630. var subMat = this.subMaterials[matIndex];
  23631. if (subMat) {
  23632. serializationObject.materials.push(subMat.id);
  23633. }
  23634. else {
  23635. serializationObject.materials.push(null);
  23636. }
  23637. }
  23638. return serializationObject;
  23639. };
  23640. return MultiMaterial;
  23641. })(BABYLON.Material);
  23642. BABYLON.MultiMaterial = MultiMaterial;
  23643. })(BABYLON || (BABYLON = {}));
  23644. var BABYLON;
  23645. (function (BABYLON) {
  23646. var SceneLoader = (function () {
  23647. function SceneLoader() {
  23648. }
  23649. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23650. get: function () {
  23651. return 0;
  23652. },
  23653. enumerable: true,
  23654. configurable: true
  23655. });
  23656. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23657. get: function () {
  23658. return 1;
  23659. },
  23660. enumerable: true,
  23661. configurable: true
  23662. });
  23663. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23664. get: function () {
  23665. return 2;
  23666. },
  23667. enumerable: true,
  23668. configurable: true
  23669. });
  23670. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23671. get: function () {
  23672. return 3;
  23673. },
  23674. enumerable: true,
  23675. configurable: true
  23676. });
  23677. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23678. get: function () {
  23679. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23680. },
  23681. set: function (value) {
  23682. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23683. },
  23684. enumerable: true,
  23685. configurable: true
  23686. });
  23687. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23688. get: function () {
  23689. return SceneLoader._ShowLoadingScreen;
  23690. },
  23691. set: function (value) {
  23692. SceneLoader._ShowLoadingScreen = value;
  23693. },
  23694. enumerable: true,
  23695. configurable: true
  23696. });
  23697. Object.defineProperty(SceneLoader, "loggingLevel", {
  23698. get: function () {
  23699. return SceneLoader._loggingLevel;
  23700. },
  23701. set: function (value) {
  23702. SceneLoader._loggingLevel = value;
  23703. },
  23704. enumerable: true,
  23705. configurable: true
  23706. });
  23707. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23708. var dotPosition = sceneFilename.lastIndexOf(".");
  23709. var queryStringPosition = sceneFilename.indexOf("?");
  23710. if (queryStringPosition === -1) {
  23711. queryStringPosition = sceneFilename.length;
  23712. }
  23713. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23714. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23715. var plugin = this._registeredPlugins[index];
  23716. if (plugin.extensions.indexOf(extension) !== -1) {
  23717. return plugin;
  23718. }
  23719. }
  23720. return this._registeredPlugins[0];
  23721. };
  23722. // Public functions
  23723. SceneLoader.GetPluginForExtension = function (extension) {
  23724. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23725. var plugin = this._registeredPlugins[index];
  23726. if (plugin.extensions.indexOf(extension) !== -1) {
  23727. return plugin;
  23728. }
  23729. }
  23730. return null;
  23731. };
  23732. SceneLoader.RegisterPlugin = function (plugin) {
  23733. plugin.extensions = plugin.extensions.toLowerCase();
  23734. SceneLoader._registeredPlugins.push(plugin);
  23735. };
  23736. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23737. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23738. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23739. return;
  23740. }
  23741. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23742. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23743. return;
  23744. }
  23745. var loadingToken = {};
  23746. scene._addPendingData(loadingToken);
  23747. var manifestChecked = function (success) {
  23748. scene.database = database;
  23749. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23750. var importMeshFromData = function (data) {
  23751. var meshes = [];
  23752. var particleSystems = [];
  23753. var skeletons = [];
  23754. try {
  23755. if (plugin.importMesh) {
  23756. var syncedPlugin = plugin;
  23757. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23758. if (onerror) {
  23759. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23760. }
  23761. scene._removePendingData(loadingToken);
  23762. return;
  23763. }
  23764. if (onsuccess) {
  23765. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23766. onsuccess(meshes, particleSystems, skeletons);
  23767. scene._removePendingData(loadingToken);
  23768. }
  23769. }
  23770. else {
  23771. var asyncedPlugin = plugin;
  23772. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23773. if (onsuccess) {
  23774. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23775. onsuccess(meshes, particleSystems, skeletons);
  23776. scene._removePendingData(loadingToken);
  23777. }
  23778. }, function () {
  23779. if (onerror) {
  23780. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23781. }
  23782. scene._removePendingData(loadingToken);
  23783. });
  23784. }
  23785. }
  23786. catch (e) {
  23787. if (onerror) {
  23788. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  23789. }
  23790. scene._removePendingData(loadingToken);
  23791. }
  23792. };
  23793. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23794. // Direct load
  23795. importMeshFromData(sceneFilename.substr(5));
  23796. return;
  23797. }
  23798. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23799. importMeshFromData(data);
  23800. }, progressCallBack, database);
  23801. };
  23802. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23803. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23804. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23805. }
  23806. else {
  23807. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23808. manifestChecked(true);
  23809. }
  23810. };
  23811. /**
  23812. * Load a scene
  23813. * @param rootUrl a string that defines the root url for scene and resources
  23814. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23815. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23816. */
  23817. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23818. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23819. };
  23820. /**
  23821. * Append a scene
  23822. * @param rootUrl a string that defines the root url for scene and resources
  23823. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23824. * @param scene is the instance of BABYLON.Scene to append to
  23825. */
  23826. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23827. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23828. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23829. return;
  23830. }
  23831. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23832. var database;
  23833. var loadingToken = {};
  23834. scene._addPendingData(loadingToken);
  23835. if (SceneLoader.ShowLoadingScreen) {
  23836. scene.getEngine().displayLoadingUI();
  23837. }
  23838. var loadSceneFromData = function (data) {
  23839. scene.database = database;
  23840. if (plugin.load) {
  23841. var syncedPlugin = plugin;
  23842. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23843. if (onerror) {
  23844. onerror(scene);
  23845. }
  23846. scene._removePendingData(loadingToken);
  23847. scene.getEngine().hideLoadingUI();
  23848. return;
  23849. }
  23850. if (onsuccess) {
  23851. onsuccess(scene);
  23852. }
  23853. scene._removePendingData(loadingToken);
  23854. }
  23855. else {
  23856. var asyncedPlugin = plugin;
  23857. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23858. if (onsuccess) {
  23859. onsuccess(scene);
  23860. }
  23861. }, function () {
  23862. if (onerror) {
  23863. onerror(scene);
  23864. }
  23865. scene._removePendingData(loadingToken);
  23866. scene.getEngine().hideLoadingUI();
  23867. });
  23868. }
  23869. if (SceneLoader.ShowLoadingScreen) {
  23870. scene.executeWhenReady(function () {
  23871. scene.getEngine().hideLoadingUI();
  23872. });
  23873. }
  23874. };
  23875. var manifestChecked = function (success) {
  23876. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23877. };
  23878. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23879. // Direct load
  23880. loadSceneFromData(sceneFilename.substr(5));
  23881. return;
  23882. }
  23883. if (rootUrl.indexOf("file:") === -1) {
  23884. if (scene.getEngine().enableOfflineSupport) {
  23885. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23886. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23887. }
  23888. else {
  23889. manifestChecked(true);
  23890. }
  23891. }
  23892. else {
  23893. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23894. }
  23895. };
  23896. // Flags
  23897. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23898. SceneLoader._ShowLoadingScreen = true;
  23899. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23900. // Members
  23901. SceneLoader._registeredPlugins = new Array();
  23902. return SceneLoader;
  23903. })();
  23904. BABYLON.SceneLoader = SceneLoader;
  23905. ;
  23906. })(BABYLON || (BABYLON = {}));
  23907. var BABYLON;
  23908. (function (BABYLON) {
  23909. var Internals;
  23910. (function (Internals) {
  23911. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23912. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23913. var parsedMaterial = parsedData.materials[index];
  23914. if (parsedMaterial.id === id) {
  23915. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23916. }
  23917. }
  23918. return null;
  23919. };
  23920. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23921. names = (names instanceof Array) ? names : [names];
  23922. for (var i in names) {
  23923. if (mesh.name === names[i]) {
  23924. hierarchyIds.push(mesh.id);
  23925. return true;
  23926. }
  23927. }
  23928. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23929. hierarchyIds.push(mesh.id);
  23930. return true;
  23931. }
  23932. return false;
  23933. };
  23934. var logOperation = function (operation, producer) {
  23935. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23936. };
  23937. BABYLON.SceneLoader.RegisterPlugin({
  23938. extensions: ".babylon",
  23939. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23940. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23941. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23942. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23943. // and avoid problems with multiple concurrent .babylon loads.
  23944. var log = "importMesh has failed JSON parse";
  23945. try {
  23946. var parsedData = JSON.parse(data);
  23947. log = "";
  23948. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23949. var loadedSkeletonsIds = [];
  23950. var loadedMaterialsIds = [];
  23951. var hierarchyIds = [];
  23952. var index;
  23953. var cache;
  23954. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23955. var parsedMesh = parsedData.meshes[index];
  23956. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23957. if (meshesNames instanceof Array) {
  23958. // Remove found mesh name from list.
  23959. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23960. }
  23961. //Geometry?
  23962. if (parsedMesh.geometryId) {
  23963. //does the file contain geometries?
  23964. if (parsedData.geometries) {
  23965. //find the correct geometry and add it to the scene
  23966. var found = false;
  23967. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23968. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23969. return;
  23970. }
  23971. else {
  23972. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23973. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23974. switch (geometryType) {
  23975. case "boxes":
  23976. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23977. break;
  23978. case "spheres":
  23979. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23980. break;
  23981. case "cylinders":
  23982. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23983. break;
  23984. case "toruses":
  23985. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23986. break;
  23987. case "grounds":
  23988. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23989. break;
  23990. case "planes":
  23991. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23992. break;
  23993. case "torusKnots":
  23994. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23995. break;
  23996. case "vertexData":
  23997. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23998. break;
  23999. }
  24000. found = true;
  24001. }
  24002. });
  24003. }
  24004. });
  24005. if (!found) {
  24006. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  24007. }
  24008. }
  24009. }
  24010. // Material ?
  24011. if (parsedMesh.materialId) {
  24012. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  24013. if (!materialFound && parsedData.multiMaterials) {
  24014. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  24015. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  24016. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  24017. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  24018. var subMatId = parsedMultiMaterial.materials[matIndex];
  24019. loadedMaterialsIds.push(subMatId);
  24020. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  24021. log += "\n\tMaterial " + mat.toString(fullDetails);
  24022. }
  24023. loadedMaterialsIds.push(parsedMultiMaterial.id);
  24024. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24025. materialFound = true;
  24026. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  24027. break;
  24028. }
  24029. }
  24030. }
  24031. if (!materialFound) {
  24032. loadedMaterialsIds.push(parsedMesh.materialId);
  24033. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  24034. if (!mat) {
  24035. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  24036. }
  24037. else {
  24038. log += "\n\tMaterial " + mat.toString(fullDetails);
  24039. }
  24040. }
  24041. }
  24042. // Skeleton ?
  24043. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  24044. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  24045. if (!skeletonAlreadyLoaded) {
  24046. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  24047. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  24048. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  24049. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24050. skeletons.push(skeleton);
  24051. loadedSkeletonsIds.push(parsedSkeleton.id);
  24052. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  24053. }
  24054. }
  24055. }
  24056. }
  24057. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24058. meshes.push(mesh);
  24059. log += "\n\tMesh " + mesh.toString(fullDetails);
  24060. }
  24061. }
  24062. // Connecting parents
  24063. var currentMesh;
  24064. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24065. currentMesh = scene.meshes[index];
  24066. if (currentMesh._waitingParentId) {
  24067. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  24068. currentMesh._waitingParentId = undefined;
  24069. }
  24070. }
  24071. // freeze and compute world matrix application
  24072. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24073. currentMesh = scene.meshes[index];
  24074. if (currentMesh._waitingFreezeWorldMatrix) {
  24075. currentMesh.freezeWorldMatrix();
  24076. currentMesh._waitingFreezeWorldMatrix = undefined;
  24077. }
  24078. else {
  24079. currentMesh.computeWorldMatrix(true);
  24080. }
  24081. }
  24082. // Particles
  24083. if (parsedData.particleSystems) {
  24084. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24085. var parsedParticleSystem = parsedData.particleSystems[index];
  24086. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  24087. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  24088. }
  24089. }
  24090. }
  24091. return true;
  24092. }
  24093. catch (err) {
  24094. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  24095. log = null;
  24096. throw err;
  24097. }
  24098. finally {
  24099. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24100. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24101. }
  24102. }
  24103. },
  24104. load: function (scene, data, rootUrl) {
  24105. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  24106. // when SceneLoader.debugLogging = true (default), or exception encountered.
  24107. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  24108. // and avoid problems with multiple concurrent .babylon loads.
  24109. var log = "importScene has failed JSON parse";
  24110. try {
  24111. var parsedData = JSON.parse(data);
  24112. log = "";
  24113. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  24114. // Scene
  24115. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  24116. scene.autoClear = parsedData.autoClear;
  24117. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  24118. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  24119. if (parsedData.gravity) {
  24120. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  24121. }
  24122. // Fog
  24123. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  24124. scene.fogMode = parsedData.fogMode;
  24125. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  24126. scene.fogStart = parsedData.fogStart;
  24127. scene.fogEnd = parsedData.fogEnd;
  24128. scene.fogDensity = parsedData.fogDensity;
  24129. log += "\tFog mode for scene: ";
  24130. switch (scene.fogMode) {
  24131. // getters not compiling, so using hardcoded
  24132. case 1:
  24133. log += "exp\n";
  24134. break;
  24135. case 2:
  24136. log += "exp2\n";
  24137. break;
  24138. case 3:
  24139. log += "linear\n";
  24140. break;
  24141. }
  24142. }
  24143. //Physics
  24144. if (parsedData.physicsEnabled) {
  24145. var physicsPlugin;
  24146. if (parsedData.physicsEngine === "cannon") {
  24147. physicsPlugin = new BABYLON.CannonJSPlugin();
  24148. }
  24149. else if (parsedData.physicsEngine === "oimo") {
  24150. physicsPlugin = new BABYLON.OimoJSPlugin();
  24151. }
  24152. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  24153. //else - default engine, which is currently oimo
  24154. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  24155. scene.enablePhysics(physicsGravity, physicsPlugin);
  24156. }
  24157. //collisions, if defined. otherwise, default is true
  24158. if (parsedData.collisionsEnabled != undefined) {
  24159. scene.collisionsEnabled = parsedData.collisionsEnabled;
  24160. }
  24161. scene.workerCollisions = !!parsedData.workerCollisions;
  24162. var index;
  24163. var cache;
  24164. // Lights
  24165. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  24166. var parsedLight = parsedData.lights[index];
  24167. var light = BABYLON.Light.Parse(parsedLight, scene);
  24168. log += (index === 0 ? "\n\tLights:" : "");
  24169. log += "\n\t\t" + light.toString(fullDetails);
  24170. }
  24171. // Animations
  24172. if (parsedData.animations) {
  24173. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  24174. var parsedAnimation = parsedData.animations[index];
  24175. var animation = BABYLON.Animation.Parse(parsedAnimation);
  24176. scene.animations.push(animation);
  24177. log += (index === 0 ? "\n\tAnimations:" : "");
  24178. log += "\n\t\t" + animation.toString(fullDetails);
  24179. }
  24180. }
  24181. if (parsedData.autoAnimate) {
  24182. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  24183. }
  24184. // Materials
  24185. if (parsedData.materials) {
  24186. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  24187. var parsedMaterial = parsedData.materials[index];
  24188. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  24189. log += (index === 0 ? "\n\tMaterials:" : "");
  24190. log += "\n\t\t" + mat.toString(fullDetails);
  24191. }
  24192. }
  24193. if (parsedData.multiMaterials) {
  24194. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  24195. var parsedMultiMaterial = parsedData.multiMaterials[index];
  24196. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  24197. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  24198. log += "\n\t\t" + mmat.toString(fullDetails);
  24199. }
  24200. }
  24201. // Skeletons
  24202. if (parsedData.skeletons) {
  24203. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  24204. var parsedSkeleton = parsedData.skeletons[index];
  24205. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24206. log += (index === 0 ? "\n\tSkeletons:" : "");
  24207. log += "\n\t\t" + skeleton.toString(fullDetails);
  24208. }
  24209. }
  24210. // Geometries
  24211. var geometries = parsedData.geometries;
  24212. if (geometries) {
  24213. // Boxes
  24214. var boxes = geometries.boxes;
  24215. if (boxes) {
  24216. for (index = 0, cache = boxes.length; index < cache; index++) {
  24217. var parsedBox = boxes[index];
  24218. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24219. }
  24220. }
  24221. // Spheres
  24222. var spheres = geometries.spheres;
  24223. if (spheres) {
  24224. for (index = 0, cache = spheres.length; index < cache; index++) {
  24225. var parsedSphere = spheres[index];
  24226. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24227. }
  24228. }
  24229. // Cylinders
  24230. var cylinders = geometries.cylinders;
  24231. if (cylinders) {
  24232. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24233. var parsedCylinder = cylinders[index];
  24234. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24235. }
  24236. }
  24237. // Toruses
  24238. var toruses = geometries.toruses;
  24239. if (toruses) {
  24240. for (index = 0, cache = toruses.length; index < cache; index++) {
  24241. var parsedTorus = toruses[index];
  24242. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24243. }
  24244. }
  24245. // Grounds
  24246. var grounds = geometries.grounds;
  24247. if (grounds) {
  24248. for (index = 0, cache = grounds.length; index < cache; index++) {
  24249. var parsedGround = grounds[index];
  24250. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24251. }
  24252. }
  24253. // Planes
  24254. var planes = geometries.planes;
  24255. if (planes) {
  24256. for (index = 0, cache = planes.length; index < cache; index++) {
  24257. var parsedPlane = planes[index];
  24258. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24259. }
  24260. }
  24261. // TorusKnots
  24262. var torusKnots = geometries.torusKnots;
  24263. if (torusKnots) {
  24264. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24265. var parsedTorusKnot = torusKnots[index];
  24266. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24267. }
  24268. }
  24269. // VertexData
  24270. var vertexData = geometries.vertexData;
  24271. if (vertexData) {
  24272. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24273. var parsedVertexData = vertexData[index];
  24274. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24275. }
  24276. }
  24277. }
  24278. // Meshes
  24279. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24280. var parsedMesh = parsedData.meshes[index];
  24281. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24282. log += (index === 0 ? "\n\tMeshes:" : "");
  24283. log += "\n\t\t" + mesh.toString(fullDetails);
  24284. }
  24285. // Cameras
  24286. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24287. var parsedCamera = parsedData.cameras[index];
  24288. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24289. log += (index === 0 ? "\n\tCameras:" : "");
  24290. log += "\n\t\t" + camera.toString(fullDetails);
  24291. }
  24292. if (parsedData.activeCameraID) {
  24293. scene.setActiveCameraByID(parsedData.activeCameraID);
  24294. }
  24295. // Browsing all the graph to connect the dots
  24296. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24297. var camera = scene.cameras[index];
  24298. if (camera._waitingParentId) {
  24299. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24300. camera._waitingParentId = undefined;
  24301. }
  24302. }
  24303. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24304. var light = scene.lights[index];
  24305. if (light._waitingParentId) {
  24306. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24307. light._waitingParentId = undefined;
  24308. }
  24309. }
  24310. // Sounds
  24311. var loadedSounds = [];
  24312. var loadedSound;
  24313. if (BABYLON.AudioEngine && parsedData.sounds) {
  24314. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24315. var parsedSound = parsedData.sounds[index];
  24316. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24317. if (!parsedSound.url)
  24318. parsedSound.url = parsedSound.name;
  24319. if (!loadedSounds[parsedSound.url]) {
  24320. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24321. loadedSounds[parsedSound.url] = loadedSound;
  24322. }
  24323. else {
  24324. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24325. }
  24326. }
  24327. else {
  24328. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24329. }
  24330. }
  24331. }
  24332. loadedSounds = [];
  24333. // Connect parents & children and parse actions
  24334. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24335. var mesh = scene.meshes[index];
  24336. if (mesh._waitingParentId) {
  24337. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24338. mesh._waitingParentId = undefined;
  24339. }
  24340. if (mesh._waitingActions) {
  24341. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24342. mesh._waitingActions = undefined;
  24343. }
  24344. }
  24345. // freeze world matrix application
  24346. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24347. var currentMesh = scene.meshes[index];
  24348. if (currentMesh._waitingFreezeWorldMatrix) {
  24349. currentMesh.freezeWorldMatrix();
  24350. currentMesh._waitingFreezeWorldMatrix = undefined;
  24351. }
  24352. else {
  24353. currentMesh.computeWorldMatrix(true);
  24354. }
  24355. }
  24356. // Particles Systems
  24357. if (parsedData.particleSystems) {
  24358. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24359. var parsedParticleSystem = parsedData.particleSystems[index];
  24360. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24361. }
  24362. }
  24363. // Lens flares
  24364. if (parsedData.lensFlareSystems) {
  24365. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24366. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24367. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24368. }
  24369. }
  24370. // Shadows
  24371. if (parsedData.shadowGenerators) {
  24372. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24373. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24374. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24375. }
  24376. }
  24377. // Actions (scene)
  24378. if (parsedData.actions) {
  24379. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24380. }
  24381. // Finish
  24382. return true;
  24383. }
  24384. catch (err) {
  24385. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24386. log = null;
  24387. throw err;
  24388. }
  24389. finally {
  24390. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24391. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24392. }
  24393. }
  24394. }
  24395. });
  24396. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24397. })(BABYLON || (BABYLON = {}));
  24398. var BABYLON;
  24399. (function (BABYLON) {
  24400. var SpriteManager = (function () {
  24401. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24402. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24403. this.name = name;
  24404. this.cellSize = cellSize;
  24405. this.sprites = new Array();
  24406. this.renderingGroupId = 0;
  24407. this.layerMask = 0x0FFFFFFF;
  24408. this.fogEnabled = true;
  24409. this.isPickable = false;
  24410. this._vertexDeclaration = [4, 4, 4, 4];
  24411. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24412. this._capacity = capacity;
  24413. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24414. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24415. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24416. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24417. this._scene = scene;
  24418. this._scene.spriteManagers.push(this);
  24419. // VBO
  24420. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24421. var indices = [];
  24422. var index = 0;
  24423. for (var count = 0; count < capacity; count++) {
  24424. indices.push(index);
  24425. indices.push(index + 1);
  24426. indices.push(index + 2);
  24427. indices.push(index);
  24428. indices.push(index + 2);
  24429. indices.push(index + 3);
  24430. index += 4;
  24431. }
  24432. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24433. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24434. // Effects
  24435. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24436. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24437. }
  24438. Object.defineProperty(SpriteManager.prototype, "texture", {
  24439. get: function () {
  24440. return this._spriteTexture;
  24441. },
  24442. set: function (value) {
  24443. this._spriteTexture = value;
  24444. },
  24445. enumerable: true,
  24446. configurable: true
  24447. });
  24448. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24449. var arrayOffset = index * 16;
  24450. if (offsetX === 0)
  24451. offsetX = this._epsilon;
  24452. else if (offsetX === 1)
  24453. offsetX = 1 - this._epsilon;
  24454. if (offsetY === 0)
  24455. offsetY = this._epsilon;
  24456. else if (offsetY === 1)
  24457. offsetY = 1 - this._epsilon;
  24458. this._vertices[arrayOffset] = sprite.position.x;
  24459. this._vertices[arrayOffset + 1] = sprite.position.y;
  24460. this._vertices[arrayOffset + 2] = sprite.position.z;
  24461. this._vertices[arrayOffset + 3] = sprite.angle;
  24462. this._vertices[arrayOffset + 4] = sprite.width;
  24463. this._vertices[arrayOffset + 5] = sprite.height;
  24464. this._vertices[arrayOffset + 6] = offsetX;
  24465. this._vertices[arrayOffset + 7] = offsetY;
  24466. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24467. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24468. var offset = (sprite.cellIndex / rowSize) >> 0;
  24469. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24470. this._vertices[arrayOffset + 11] = offset;
  24471. // Color
  24472. this._vertices[arrayOffset + 12] = sprite.color.r;
  24473. this._vertices[arrayOffset + 13] = sprite.color.g;
  24474. this._vertices[arrayOffset + 14] = sprite.color.b;
  24475. this._vertices[arrayOffset + 15] = sprite.color.a;
  24476. };
  24477. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24478. var count = Math.min(this._capacity, this.sprites.length);
  24479. var min = BABYLON.Vector3.Zero();
  24480. var max = BABYLON.Vector3.Zero();
  24481. var distance = Number.MAX_VALUE;
  24482. var currentSprite;
  24483. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24484. var cameraView = camera.getViewMatrix();
  24485. for (var index = 0; index < count; index++) {
  24486. var sprite = this.sprites[index];
  24487. if (!sprite) {
  24488. continue;
  24489. }
  24490. if (predicate) {
  24491. if (!predicate(sprite)) {
  24492. continue;
  24493. }
  24494. }
  24495. else if (!sprite.isPickable) {
  24496. continue;
  24497. }
  24498. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24499. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24500. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24501. if (ray.intersectsBoxMinMax(min, max)) {
  24502. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24503. if (distance > currentDistance) {
  24504. distance = currentDistance;
  24505. currentSprite = sprite;
  24506. if (fastCheck) {
  24507. break;
  24508. }
  24509. }
  24510. }
  24511. }
  24512. if (currentSprite) {
  24513. var result = new BABYLON.PickingInfo();
  24514. result.hit = true;
  24515. result.pickedSprite = currentSprite;
  24516. result.distance = distance;
  24517. return result;
  24518. }
  24519. return null;
  24520. };
  24521. SpriteManager.prototype.render = function () {
  24522. // Check
  24523. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24524. return;
  24525. var engine = this._scene.getEngine();
  24526. var baseSize = this._spriteTexture.getBaseSize();
  24527. // Sprites
  24528. var deltaTime = engine.getDeltaTime();
  24529. var max = Math.min(this._capacity, this.sprites.length);
  24530. var rowSize = baseSize.width / this.cellSize;
  24531. var offset = 0;
  24532. for (var index = 0; index < max; index++) {
  24533. var sprite = this.sprites[index];
  24534. if (!sprite) {
  24535. continue;
  24536. }
  24537. sprite._animate(deltaTime);
  24538. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24539. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24540. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24541. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24542. }
  24543. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24544. // Render
  24545. var effect = this._effectBase;
  24546. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24547. effect = this._effectFog;
  24548. }
  24549. engine.enableEffect(effect);
  24550. var viewMatrix = this._scene.getViewMatrix();
  24551. effect.setTexture("diffuseSampler", this._spriteTexture);
  24552. effect.setMatrix("view", viewMatrix);
  24553. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24554. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24555. // Fog
  24556. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24557. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24558. effect.setColor3("vFogColor", this._scene.fogColor);
  24559. }
  24560. // VBOs
  24561. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24562. // Draw order
  24563. engine.setDepthFunctionToLessOrEqual();
  24564. effect.setBool("alphaTest", true);
  24565. engine.setColorWrite(false);
  24566. engine.draw(true, 0, max * 6);
  24567. engine.setColorWrite(true);
  24568. effect.setBool("alphaTest", false);
  24569. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24570. engine.draw(true, 0, max * 6);
  24571. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24572. };
  24573. SpriteManager.prototype.dispose = function () {
  24574. if (this._vertexBuffer) {
  24575. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24576. this._vertexBuffer = null;
  24577. }
  24578. if (this._indexBuffer) {
  24579. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24580. this._indexBuffer = null;
  24581. }
  24582. if (this._spriteTexture) {
  24583. this._spriteTexture.dispose();
  24584. this._spriteTexture = null;
  24585. }
  24586. // Remove from scene
  24587. var index = this._scene.spriteManagers.indexOf(this);
  24588. this._scene.spriteManagers.splice(index, 1);
  24589. // Callback
  24590. if (this.onDispose) {
  24591. this.onDispose();
  24592. }
  24593. };
  24594. return SpriteManager;
  24595. })();
  24596. BABYLON.SpriteManager = SpriteManager;
  24597. })(BABYLON || (BABYLON = {}));
  24598. var BABYLON;
  24599. (function (BABYLON) {
  24600. var Sprite = (function () {
  24601. function Sprite(name, manager) {
  24602. this.name = name;
  24603. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24604. this.width = 1.0;
  24605. this.height = 1.0;
  24606. this.angle = 0;
  24607. this.cellIndex = 0;
  24608. this.invertU = 0;
  24609. this.invertV = 0;
  24610. this.animations = new Array();
  24611. this.isPickable = false;
  24612. this._animationStarted = false;
  24613. this._loopAnimation = false;
  24614. this._fromIndex = 0;
  24615. this._toIndex = 0;
  24616. this._delay = 0;
  24617. this._direction = 1;
  24618. this._frameCount = 0;
  24619. this._time = 0;
  24620. this._manager = manager;
  24621. this._manager.sprites.push(this);
  24622. this.position = BABYLON.Vector3.Zero();
  24623. }
  24624. Object.defineProperty(Sprite.prototype, "size", {
  24625. get: function () {
  24626. return this.width;
  24627. },
  24628. set: function (value) {
  24629. this.width = value;
  24630. this.height = value;
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24636. this._fromIndex = from;
  24637. this._toIndex = to;
  24638. this._loopAnimation = loop;
  24639. this._delay = delay;
  24640. this._animationStarted = true;
  24641. this._direction = from < to ? 1 : -1;
  24642. this.cellIndex = from;
  24643. this._time = 0;
  24644. };
  24645. Sprite.prototype.stopAnimation = function () {
  24646. this._animationStarted = false;
  24647. };
  24648. Sprite.prototype._animate = function (deltaTime) {
  24649. if (!this._animationStarted)
  24650. return;
  24651. this._time += deltaTime;
  24652. if (this._time > this._delay) {
  24653. this._time = this._time % this._delay;
  24654. this.cellIndex += this._direction;
  24655. if (this.cellIndex == this._toIndex) {
  24656. if (this._loopAnimation) {
  24657. this.cellIndex = this._fromIndex;
  24658. }
  24659. else {
  24660. this._animationStarted = false;
  24661. if (this.disposeWhenFinishedAnimating) {
  24662. this.dispose();
  24663. }
  24664. }
  24665. }
  24666. }
  24667. };
  24668. Sprite.prototype.dispose = function () {
  24669. for (var i = 0; i < this._manager.sprites.length; i++) {
  24670. if (this._manager.sprites[i] == this) {
  24671. this._manager.sprites.splice(i, 1);
  24672. }
  24673. }
  24674. };
  24675. return Sprite;
  24676. })();
  24677. BABYLON.Sprite = Sprite;
  24678. })(BABYLON || (BABYLON = {}));
  24679. var BABYLON;
  24680. (function (BABYLON) {
  24681. var Layer = (function () {
  24682. function Layer(name, imgUrl, scene, isBackground, color) {
  24683. this.name = name;
  24684. this.scale = new BABYLON.Vector2(1, 1);
  24685. this.offset = new BABYLON.Vector2(0, 0);
  24686. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24687. this._vertexDeclaration = [2];
  24688. this._vertexStrideSize = 2 * 4;
  24689. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24690. this.isBackground = isBackground === undefined ? true : isBackground;
  24691. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24692. this._scene = scene;
  24693. this._scene.layers.push(this);
  24694. // VBO
  24695. var vertices = [];
  24696. vertices.push(1, 1);
  24697. vertices.push(-1, 1);
  24698. vertices.push(-1, -1);
  24699. vertices.push(1, -1);
  24700. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24701. // Indices
  24702. var indices = [];
  24703. indices.push(0);
  24704. indices.push(1);
  24705. indices.push(2);
  24706. indices.push(0);
  24707. indices.push(2);
  24708. indices.push(3);
  24709. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24710. // Effects
  24711. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24712. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24713. }
  24714. Layer.prototype.render = function () {
  24715. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24716. // Check
  24717. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24718. return;
  24719. var engine = this._scene.getEngine();
  24720. if (this.onBeforeRender) {
  24721. this.onBeforeRender();
  24722. }
  24723. // Render
  24724. engine.enableEffect(currentEffect);
  24725. engine.setState(false);
  24726. // Texture
  24727. currentEffect.setTexture("textureSampler", this.texture);
  24728. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24729. // Color
  24730. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24731. // Scale / offset
  24732. currentEffect.setVector2("offset", this.offset);
  24733. currentEffect.setVector2("scale", this.scale);
  24734. // VBOs
  24735. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24736. // Draw order
  24737. if (!this._alphaTestEffect) {
  24738. engine.setAlphaMode(this.alphaBlendingMode);
  24739. engine.draw(true, 0, 6);
  24740. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24741. }
  24742. else {
  24743. engine.draw(true, 0, 6);
  24744. }
  24745. if (this.onAfterRender) {
  24746. this.onAfterRender();
  24747. }
  24748. };
  24749. Layer.prototype.dispose = function () {
  24750. if (this._vertexBuffer) {
  24751. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24752. this._vertexBuffer = null;
  24753. }
  24754. if (this._indexBuffer) {
  24755. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24756. this._indexBuffer = null;
  24757. }
  24758. if (this.texture) {
  24759. this.texture.dispose();
  24760. this.texture = null;
  24761. }
  24762. // Remove from scene
  24763. var index = this._scene.layers.indexOf(this);
  24764. this._scene.layers.splice(index, 1);
  24765. // Callback
  24766. if (this.onDispose) {
  24767. this.onDispose();
  24768. }
  24769. };
  24770. return Layer;
  24771. })();
  24772. BABYLON.Layer = Layer;
  24773. })(BABYLON || (BABYLON = {}));
  24774. var BABYLON;
  24775. (function (BABYLON) {
  24776. var Particle = (function () {
  24777. function Particle() {
  24778. this.position = BABYLON.Vector3.Zero();
  24779. this.direction = BABYLON.Vector3.Zero();
  24780. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24781. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24782. this.lifeTime = 1.0;
  24783. this.age = 0;
  24784. this.size = 0;
  24785. this.angle = 0;
  24786. this.angularSpeed = 0;
  24787. }
  24788. Particle.prototype.copyTo = function (other) {
  24789. other.position.copyFrom(this.position);
  24790. other.direction.copyFrom(this.direction);
  24791. other.color.copyFrom(this.color);
  24792. other.colorStep.copyFrom(this.colorStep);
  24793. other.lifeTime = this.lifeTime;
  24794. other.age = this.age;
  24795. other.size = this.size;
  24796. other.angle = this.angle;
  24797. other.angularSpeed = this.angularSpeed;
  24798. };
  24799. return Particle;
  24800. })();
  24801. BABYLON.Particle = Particle;
  24802. })(BABYLON || (BABYLON = {}));
  24803. var BABYLON;
  24804. (function (BABYLON) {
  24805. var randomNumber = function (min, max) {
  24806. if (min === max) {
  24807. return (min);
  24808. }
  24809. var random = Math.random();
  24810. return ((random * (max - min)) + min);
  24811. };
  24812. var ParticleSystem = (function () {
  24813. function ParticleSystem(name, capacity, scene, customEffect) {
  24814. var _this = this;
  24815. this.name = name;
  24816. // Members
  24817. this.animations = [];
  24818. this.renderingGroupId = 0;
  24819. this.emitter = null;
  24820. this.emitRate = 10;
  24821. this.manualEmitCount = -1;
  24822. this.updateSpeed = 0.01;
  24823. this.targetStopDuration = 0;
  24824. this.disposeOnStop = false;
  24825. this.minEmitPower = 1;
  24826. this.maxEmitPower = 1;
  24827. this.minLifeTime = 1;
  24828. this.maxLifeTime = 1;
  24829. this.minSize = 1;
  24830. this.maxSize = 1;
  24831. this.minAngularSpeed = 0;
  24832. this.maxAngularSpeed = 0;
  24833. this.layerMask = 0x0FFFFFFF;
  24834. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24835. this.forceDepthWrite = false;
  24836. this.gravity = BABYLON.Vector3.Zero();
  24837. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24838. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24839. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24840. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24841. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24842. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24843. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24844. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24845. this.particles = new Array();
  24846. this._vertexDeclaration = [3, 4, 4];
  24847. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24848. this._stockParticles = new Array();
  24849. this._newPartsExcess = 0;
  24850. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24851. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24852. this._scaledDirection = BABYLON.Vector3.Zero();
  24853. this._scaledGravity = BABYLON.Vector3.Zero();
  24854. this._currentRenderId = -1;
  24855. this._started = false;
  24856. this._stopped = false;
  24857. this._actualFrame = 0;
  24858. this.id = name;
  24859. this._capacity = capacity;
  24860. this._scene = scene;
  24861. this._customEffect = customEffect;
  24862. scene.particleSystems.push(this);
  24863. // VBO
  24864. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24865. var indices = [];
  24866. var index = 0;
  24867. for (var count = 0; count < capacity; count++) {
  24868. indices.push(index);
  24869. indices.push(index + 1);
  24870. indices.push(index + 2);
  24871. indices.push(index);
  24872. indices.push(index + 2);
  24873. indices.push(index + 3);
  24874. index += 4;
  24875. }
  24876. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24877. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24878. // Default behaviors
  24879. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24880. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24881. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24882. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24883. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24884. };
  24885. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24886. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24887. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24888. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24890. };
  24891. this.updateFunction = function (particles) {
  24892. for (var index = 0; index < particles.length; index++) {
  24893. var particle = particles[index];
  24894. particle.age += _this._scaledUpdateSpeed;
  24895. if (particle.age >= particle.lifeTime) {
  24896. _this.recycleParticle(particle);
  24897. index--;
  24898. continue;
  24899. }
  24900. else {
  24901. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24902. particle.color.addInPlace(_this._scaledColorStep);
  24903. if (particle.color.a < 0)
  24904. particle.color.a = 0;
  24905. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24906. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24907. particle.position.addInPlace(_this._scaledDirection);
  24908. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24909. particle.direction.addInPlace(_this._scaledGravity);
  24910. }
  24911. }
  24912. };
  24913. }
  24914. ParticleSystem.prototype.recycleParticle = function (particle) {
  24915. var lastParticle = this.particles.pop();
  24916. if (lastParticle !== particle) {
  24917. lastParticle.copyTo(particle);
  24918. this._stockParticles.push(lastParticle);
  24919. }
  24920. };
  24921. ParticleSystem.prototype.getCapacity = function () {
  24922. return this._capacity;
  24923. };
  24924. ParticleSystem.prototype.isAlive = function () {
  24925. return this._alive;
  24926. };
  24927. ParticleSystem.prototype.isStarted = function () {
  24928. return this._started;
  24929. };
  24930. ParticleSystem.prototype.start = function () {
  24931. this._started = true;
  24932. this._stopped = false;
  24933. this._actualFrame = 0;
  24934. };
  24935. ParticleSystem.prototype.stop = function () {
  24936. this._stopped = true;
  24937. };
  24938. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24939. var offset = index * 11;
  24940. this._vertices[offset] = particle.position.x;
  24941. this._vertices[offset + 1] = particle.position.y;
  24942. this._vertices[offset + 2] = particle.position.z;
  24943. this._vertices[offset + 3] = particle.color.r;
  24944. this._vertices[offset + 4] = particle.color.g;
  24945. this._vertices[offset + 5] = particle.color.b;
  24946. this._vertices[offset + 6] = particle.color.a;
  24947. this._vertices[offset + 7] = particle.angle;
  24948. this._vertices[offset + 8] = particle.size;
  24949. this._vertices[offset + 9] = offsetX;
  24950. this._vertices[offset + 10] = offsetY;
  24951. };
  24952. ParticleSystem.prototype._update = function (newParticles) {
  24953. // Update current
  24954. this._alive = this.particles.length > 0;
  24955. this.updateFunction(this.particles);
  24956. // Add new ones
  24957. var worldMatrix;
  24958. if (this.emitter.position) {
  24959. worldMatrix = this.emitter.getWorldMatrix();
  24960. }
  24961. else {
  24962. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24963. }
  24964. var particle;
  24965. for (var index = 0; index < newParticles; index++) {
  24966. if (this.particles.length === this._capacity) {
  24967. break;
  24968. }
  24969. if (this._stockParticles.length !== 0) {
  24970. particle = this._stockParticles.pop();
  24971. particle.age = 0;
  24972. }
  24973. else {
  24974. particle = new BABYLON.Particle();
  24975. }
  24976. this.particles.push(particle);
  24977. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24978. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24979. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24980. particle.size = randomNumber(this.minSize, this.maxSize);
  24981. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24982. this.startPositionFunction(worldMatrix, particle.position, particle);
  24983. var step = randomNumber(0, 1.0);
  24984. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24985. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24986. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24987. }
  24988. };
  24989. ParticleSystem.prototype._getEffect = function () {
  24990. if (this._customEffect) {
  24991. return this._customEffect;
  24992. }
  24993. ;
  24994. var defines = [];
  24995. if (this._scene.clipPlane) {
  24996. defines.push("#define CLIPPLANE");
  24997. }
  24998. // Effect
  24999. var join = defines.join("\n");
  25000. if (this._cachedDefines !== join) {
  25001. this._cachedDefines = join;
  25002. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  25003. }
  25004. return this._effect;
  25005. };
  25006. ParticleSystem.prototype.animate = function () {
  25007. if (!this._started)
  25008. return;
  25009. var effect = this._getEffect();
  25010. // Check
  25011. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  25012. return;
  25013. if (this._currentRenderId === this._scene.getRenderId()) {
  25014. return;
  25015. }
  25016. this._currentRenderId = this._scene.getRenderId();
  25017. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  25018. // determine the number of particles we need to create
  25019. var newParticles;
  25020. if (this.manualEmitCount > -1) {
  25021. newParticles = this.manualEmitCount;
  25022. this._newPartsExcess = 0;
  25023. this.manualEmitCount = 0;
  25024. }
  25025. else {
  25026. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  25027. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  25028. }
  25029. if (this._newPartsExcess > 1.0) {
  25030. newParticles += this._newPartsExcess >> 0;
  25031. this._newPartsExcess -= this._newPartsExcess >> 0;
  25032. }
  25033. this._alive = false;
  25034. if (!this._stopped) {
  25035. this._actualFrame += this._scaledUpdateSpeed;
  25036. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  25037. this.stop();
  25038. }
  25039. else {
  25040. newParticles = 0;
  25041. }
  25042. this._update(newParticles);
  25043. // Stopped?
  25044. if (this._stopped) {
  25045. if (!this._alive) {
  25046. this._started = false;
  25047. if (this.disposeOnStop) {
  25048. this._scene._toBeDisposed.push(this);
  25049. }
  25050. }
  25051. }
  25052. // Update VBO
  25053. var offset = 0;
  25054. for (var index = 0; index < this.particles.length; index++) {
  25055. var particle = this.particles[index];
  25056. this._appendParticleVertex(offset++, particle, 0, 0);
  25057. this._appendParticleVertex(offset++, particle, 1, 0);
  25058. this._appendParticleVertex(offset++, particle, 1, 1);
  25059. this._appendParticleVertex(offset++, particle, 0, 1);
  25060. }
  25061. var engine = this._scene.getEngine();
  25062. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  25063. };
  25064. ParticleSystem.prototype.render = function () {
  25065. var effect = this._getEffect();
  25066. // Check
  25067. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  25068. return 0;
  25069. var engine = this._scene.getEngine();
  25070. // Render
  25071. engine.enableEffect(effect);
  25072. engine.setState(false);
  25073. var viewMatrix = this._scene.getViewMatrix();
  25074. effect.setTexture("diffuseSampler", this.particleTexture);
  25075. effect.setMatrix("view", viewMatrix);
  25076. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  25077. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  25078. if (this._scene.clipPlane) {
  25079. var clipPlane = this._scene.clipPlane;
  25080. var invView = viewMatrix.clone();
  25081. invView.invert();
  25082. effect.setMatrix("invView", invView);
  25083. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25084. }
  25085. // VBOs
  25086. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  25087. // Draw order
  25088. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  25089. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  25090. }
  25091. else {
  25092. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25093. }
  25094. if (this.forceDepthWrite) {
  25095. engine.setDepthWrite(true);
  25096. }
  25097. engine.draw(true, 0, this.particles.length * 6);
  25098. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  25099. return this.particles.length;
  25100. };
  25101. ParticleSystem.prototype.dispose = function () {
  25102. if (this._vertexBuffer) {
  25103. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  25104. this._vertexBuffer = null;
  25105. }
  25106. if (this._indexBuffer) {
  25107. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  25108. this._indexBuffer = null;
  25109. }
  25110. if (this.particleTexture) {
  25111. this.particleTexture.dispose();
  25112. this.particleTexture = null;
  25113. }
  25114. // Remove from scene
  25115. var index = this._scene.particleSystems.indexOf(this);
  25116. this._scene.particleSystems.splice(index, 1);
  25117. // Callback
  25118. if (this.onDispose) {
  25119. this.onDispose();
  25120. }
  25121. };
  25122. // Clone
  25123. ParticleSystem.prototype.clone = function (name, newEmitter) {
  25124. var result = new ParticleSystem(name, this._capacity, this._scene);
  25125. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  25126. if (newEmitter === undefined) {
  25127. newEmitter = this.emitter;
  25128. }
  25129. result.emitter = newEmitter;
  25130. if (this.particleTexture) {
  25131. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  25132. }
  25133. result.start();
  25134. return result;
  25135. };
  25136. ParticleSystem.prototype.serialize = function () {
  25137. var serializationObject = {};
  25138. serializationObject.name = this.name;
  25139. serializationObject.id = this.id;
  25140. // Emitter
  25141. if (this.emitter.position) {
  25142. serializationObject.emitterId = this.emitter.id;
  25143. }
  25144. else {
  25145. serializationObject.emitter = this.emitter.asArray();
  25146. }
  25147. serializationObject.capacity = this.getCapacity();
  25148. if (this.particleTexture) {
  25149. serializationObject.textureName = this.particleTexture.name;
  25150. }
  25151. // Animations
  25152. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25153. // Particle system
  25154. serializationObject.minAngularSpeed = this.minAngularSpeed;
  25155. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  25156. serializationObject.minSize = this.minSize;
  25157. serializationObject.maxSize = this.maxSize;
  25158. serializationObject.minEmitPower = this.minEmitPower;
  25159. serializationObject.maxEmitPower = this.maxEmitPower;
  25160. serializationObject.minLifeTime = this.minLifeTime;
  25161. serializationObject.maxLifeTime = this.maxLifeTime;
  25162. serializationObject.emitRate = this.emitRate;
  25163. serializationObject.minEmitBox = this.minEmitBox.asArray();
  25164. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  25165. serializationObject.gravity = this.gravity.asArray();
  25166. serializationObject.direction1 = this.direction1.asArray();
  25167. serializationObject.direction2 = this.direction2.asArray();
  25168. serializationObject.color1 = this.color1.asArray();
  25169. serializationObject.color2 = this.color2.asArray();
  25170. serializationObject.colorDead = this.colorDead.asArray();
  25171. serializationObject.updateSpeed = this.updateSpeed;
  25172. serializationObject.targetStopDuration = this.targetStopDuration;
  25173. serializationObject.textureMask = this.textureMask.asArray();
  25174. serializationObject.blendMode = this.blendMode;
  25175. return serializationObject;
  25176. };
  25177. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  25178. var name = parsedParticleSystem.name;
  25179. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  25180. if (parsedParticleSystem.id) {
  25181. particleSystem.id = parsedParticleSystem.id;
  25182. }
  25183. // Texture
  25184. if (parsedParticleSystem.textureName) {
  25185. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  25186. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  25187. }
  25188. // Emitter
  25189. if (parsedParticleSystem.emitterId) {
  25190. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  25191. }
  25192. else {
  25193. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  25194. }
  25195. // Animations
  25196. if (parsedParticleSystem.animations) {
  25197. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  25198. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  25199. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25200. }
  25201. }
  25202. if (parsedParticleSystem.autoAnimate) {
  25203. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  25204. }
  25205. // Particle system
  25206. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  25207. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  25208. particleSystem.minSize = parsedParticleSystem.minSize;
  25209. particleSystem.maxSize = parsedParticleSystem.maxSize;
  25210. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  25211. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  25212. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  25213. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  25214. particleSystem.emitRate = parsedParticleSystem.emitRate;
  25215. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  25216. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  25217. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  25218. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  25219. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  25220. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  25221. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  25222. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  25223. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  25224. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  25225. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  25226. particleSystem.blendMode = parsedParticleSystem.blendMode;
  25227. if (!parsedParticleSystem.preventAutoStart) {
  25228. particleSystem.start();
  25229. }
  25230. return particleSystem;
  25231. };
  25232. // Statics
  25233. ParticleSystem.BLENDMODE_ONEONE = 0;
  25234. ParticleSystem.BLENDMODE_STANDARD = 1;
  25235. return ParticleSystem;
  25236. })();
  25237. BABYLON.ParticleSystem = ParticleSystem;
  25238. })(BABYLON || (BABYLON = {}));
  25239. var BABYLON;
  25240. (function (BABYLON) {
  25241. var AnimationRange = (function () {
  25242. function AnimationRange(name, from, to) {
  25243. this.name = name;
  25244. this.from = from;
  25245. this.to = to;
  25246. }
  25247. AnimationRange.prototype.clone = function () {
  25248. return new AnimationRange(this.name, this.from, this.to);
  25249. };
  25250. return AnimationRange;
  25251. })();
  25252. BABYLON.AnimationRange = AnimationRange;
  25253. /**
  25254. * Composed of a frame, and an action function
  25255. */
  25256. var AnimationEvent = (function () {
  25257. function AnimationEvent(frame, action, onlyOnce) {
  25258. this.frame = frame;
  25259. this.action = action;
  25260. this.onlyOnce = onlyOnce;
  25261. this.isDone = false;
  25262. }
  25263. return AnimationEvent;
  25264. })();
  25265. BABYLON.AnimationEvent = AnimationEvent;
  25266. var PathCursor = (function () {
  25267. function PathCursor(path) {
  25268. this.path = path;
  25269. this._onchange = new Array();
  25270. this.value = 0;
  25271. this.animations = new Array();
  25272. }
  25273. PathCursor.prototype.getPoint = function () {
  25274. var point = this.path.getPointAtLengthPosition(this.value);
  25275. return new BABYLON.Vector3(point.x, 0, point.y);
  25276. };
  25277. PathCursor.prototype.moveAhead = function (step) {
  25278. if (step === void 0) { step = 0.002; }
  25279. this.move(step);
  25280. return this;
  25281. };
  25282. PathCursor.prototype.moveBack = function (step) {
  25283. if (step === void 0) { step = 0.002; }
  25284. this.move(-step);
  25285. return this;
  25286. };
  25287. PathCursor.prototype.move = function (step) {
  25288. if (Math.abs(step) > 1) {
  25289. throw "step size should be less than 1.";
  25290. }
  25291. this.value += step;
  25292. this.ensureLimits();
  25293. this.raiseOnChange();
  25294. return this;
  25295. };
  25296. PathCursor.prototype.ensureLimits = function () {
  25297. while (this.value > 1) {
  25298. this.value -= 1;
  25299. }
  25300. while (this.value < 0) {
  25301. this.value += 1;
  25302. }
  25303. return this;
  25304. };
  25305. // used by animation engine
  25306. PathCursor.prototype.markAsDirty = function (propertyName) {
  25307. this.ensureLimits();
  25308. this.raiseOnChange();
  25309. return this;
  25310. };
  25311. PathCursor.prototype.raiseOnChange = function () {
  25312. var _this = this;
  25313. this._onchange.forEach(function (f) { return f(_this); });
  25314. return this;
  25315. };
  25316. PathCursor.prototype.onchange = function (f) {
  25317. this._onchange.push(f);
  25318. return this;
  25319. };
  25320. return PathCursor;
  25321. })();
  25322. BABYLON.PathCursor = PathCursor;
  25323. var Animation = (function () {
  25324. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25325. this.name = name;
  25326. this.targetProperty = targetProperty;
  25327. this.framePerSecond = framePerSecond;
  25328. this.dataType = dataType;
  25329. this.loopMode = loopMode;
  25330. this.enableBlending = enableBlending;
  25331. this._offsetsCache = {};
  25332. this._highLimitsCache = {};
  25333. this._stopped = false;
  25334. this._blendingFactor = 0;
  25335. // The set of event that will be linked to this animation
  25336. this._events = new Array();
  25337. this.allowMatricesInterpolation = false;
  25338. this.blendingSpeed = 0.01;
  25339. this._ranges = {};
  25340. this.targetPropertyPath = targetProperty.split(".");
  25341. this.dataType = dataType;
  25342. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25343. }
  25344. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25345. var dataType = undefined;
  25346. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25347. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25348. }
  25349. else if (from instanceof BABYLON.Quaternion) {
  25350. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25351. }
  25352. else if (from instanceof BABYLON.Vector3) {
  25353. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25354. }
  25355. else if (from instanceof BABYLON.Vector2) {
  25356. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25357. }
  25358. else if (from instanceof BABYLON.Color3) {
  25359. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25360. }
  25361. if (dataType == undefined) {
  25362. return null;
  25363. }
  25364. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25365. var keys = [];
  25366. keys.push({ frame: 0, value: from });
  25367. keys.push({ frame: totalFrame, value: to });
  25368. animation.setKeys(keys);
  25369. if (easingFunction !== undefined) {
  25370. animation.setEasingFunction(easingFunction);
  25371. }
  25372. return animation;
  25373. };
  25374. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25375. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25376. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25377. };
  25378. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25379. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25380. node.animations.push(animation);
  25381. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25382. };
  25383. // Methods
  25384. /**
  25385. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25386. */
  25387. Animation.prototype.toString = function (fullDetails) {
  25388. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25389. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25390. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25391. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25392. if (fullDetails) {
  25393. ret += ", Ranges: {";
  25394. var first = true;
  25395. for (var name in this._ranges) {
  25396. if (!first) {
  25397. ret + ", ";
  25398. first = false;
  25399. }
  25400. ret += name;
  25401. }
  25402. ret += "}";
  25403. }
  25404. return ret;
  25405. };
  25406. /**
  25407. * Add an event to this animation.
  25408. */
  25409. Animation.prototype.addEvent = function (event) {
  25410. this._events.push(event);
  25411. };
  25412. /**
  25413. * Remove all events found at the given frame
  25414. * @param frame
  25415. */
  25416. Animation.prototype.removeEvents = function (frame) {
  25417. for (var index = 0; index < this._events.length; index++) {
  25418. if (this._events[index].frame === frame) {
  25419. this._events.splice(index, 1);
  25420. index--;
  25421. }
  25422. }
  25423. };
  25424. Animation.prototype.createRange = function (name, from, to) {
  25425. // check name not already in use; could happen for bones after serialized
  25426. if (!this._ranges[name]) {
  25427. this._ranges[name] = new AnimationRange(name, from, to);
  25428. }
  25429. };
  25430. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25431. if (deleteFrames === void 0) { deleteFrames = true; }
  25432. if (this._ranges[name]) {
  25433. if (deleteFrames) {
  25434. var from = this._ranges[name].from;
  25435. var to = this._ranges[name].to;
  25436. // this loop MUST go high to low for multiple splices to work
  25437. for (var key = this._keys.length - 1; key >= 0; key--) {
  25438. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25439. this._keys.splice(key, 1);
  25440. }
  25441. }
  25442. }
  25443. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25444. }
  25445. };
  25446. Animation.prototype.getRange = function (name) {
  25447. return this._ranges[name];
  25448. };
  25449. Animation.prototype.reset = function () {
  25450. this._offsetsCache = {};
  25451. this._highLimitsCache = {};
  25452. this.currentFrame = 0;
  25453. this._blendingFactor = 0;
  25454. this._originalBlendValue = null;
  25455. };
  25456. Animation.prototype.isStopped = function () {
  25457. return this._stopped;
  25458. };
  25459. Animation.prototype.getKeys = function () {
  25460. return this._keys;
  25461. };
  25462. Animation.prototype.getHighestFrame = function () {
  25463. var ret = 0;
  25464. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25465. if (ret < this._keys[key].frame) {
  25466. ret = this._keys[key].frame;
  25467. }
  25468. }
  25469. return ret;
  25470. };
  25471. Animation.prototype.getEasingFunction = function () {
  25472. return this._easingFunction;
  25473. };
  25474. Animation.prototype.setEasingFunction = function (easingFunction) {
  25475. this._easingFunction = easingFunction;
  25476. };
  25477. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25478. return startValue + (endValue - startValue) * gradient;
  25479. };
  25480. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25481. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25482. };
  25483. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25484. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25485. };
  25486. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25487. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25488. };
  25489. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25490. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25491. };
  25492. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25493. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25494. };
  25495. Animation.prototype.clone = function () {
  25496. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25497. if (this._keys) {
  25498. clone.setKeys(this._keys);
  25499. }
  25500. if (this._ranges) {
  25501. clone._ranges = {};
  25502. for (var name in this._ranges) {
  25503. clone._ranges[name] = this._ranges[name].clone();
  25504. }
  25505. }
  25506. return clone;
  25507. };
  25508. Animation.prototype.setKeys = function (values) {
  25509. this._keys = values.slice(0);
  25510. this._offsetsCache = {};
  25511. this._highLimitsCache = {};
  25512. };
  25513. Animation.prototype._getKeyValue = function (value) {
  25514. if (typeof value === "function") {
  25515. return value();
  25516. }
  25517. return value;
  25518. };
  25519. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25520. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25521. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25522. }
  25523. this.currentFrame = currentFrame;
  25524. // Try to get a hash to find the right key
  25525. 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));
  25526. if (this._keys[startKey].frame >= currentFrame) {
  25527. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25528. startKey--;
  25529. }
  25530. }
  25531. for (var key = startKey; key < this._keys.length; key++) {
  25532. if (this._keys[key + 1].frame >= currentFrame) {
  25533. var startValue = this._getKeyValue(this._keys[key].value);
  25534. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25535. // gradient : percent of currentFrame between the frame inf and the frame sup
  25536. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25537. // check for easingFunction and correction of gradient
  25538. if (this._easingFunction != null) {
  25539. gradient = this._easingFunction.ease(gradient);
  25540. }
  25541. switch (this.dataType) {
  25542. // Float
  25543. case Animation.ANIMATIONTYPE_FLOAT:
  25544. switch (loopMode) {
  25545. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25546. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25547. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25548. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25549. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25550. }
  25551. break;
  25552. // Quaternion
  25553. case Animation.ANIMATIONTYPE_QUATERNION:
  25554. var quaternion = null;
  25555. switch (loopMode) {
  25556. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25557. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25558. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25559. break;
  25560. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25561. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25562. break;
  25563. }
  25564. return quaternion;
  25565. // Vector3
  25566. case Animation.ANIMATIONTYPE_VECTOR3:
  25567. switch (loopMode) {
  25568. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25569. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25570. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25571. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25572. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25573. }
  25574. // Vector2
  25575. case Animation.ANIMATIONTYPE_VECTOR2:
  25576. switch (loopMode) {
  25577. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25578. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25579. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25580. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25581. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25582. }
  25583. // Color3
  25584. case Animation.ANIMATIONTYPE_COLOR3:
  25585. switch (loopMode) {
  25586. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25587. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25588. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25589. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25590. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25591. }
  25592. // Matrix
  25593. case Animation.ANIMATIONTYPE_MATRIX:
  25594. switch (loopMode) {
  25595. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25596. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25597. if (this.allowMatricesInterpolation) {
  25598. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25599. }
  25600. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25601. return startValue;
  25602. }
  25603. default:
  25604. break;
  25605. }
  25606. break;
  25607. }
  25608. }
  25609. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25610. };
  25611. Animation.prototype.setValue = function (currentValue, blend) {
  25612. if (blend === void 0) { blend = false; }
  25613. // Set value
  25614. var path;
  25615. var destination;
  25616. if (this.targetPropertyPath.length > 1) {
  25617. var property = this._target[this.targetPropertyPath[0]];
  25618. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25619. property = property[this.targetPropertyPath[index]];
  25620. }
  25621. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25622. destination = property;
  25623. }
  25624. else {
  25625. path = this.targetPropertyPath[0];
  25626. destination = this._target;
  25627. }
  25628. // Blending
  25629. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25630. if (!this._originalBlendValue) {
  25631. this._originalBlendValue = destination[path];
  25632. }
  25633. if (this._originalBlendValue.prototype) {
  25634. if (this._originalBlendValue.prototype.Lerp) {
  25635. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25636. }
  25637. else {
  25638. destination[path] = currentValue;
  25639. }
  25640. }
  25641. else {
  25642. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25643. }
  25644. this._blendingFactor += this.blendingSpeed;
  25645. }
  25646. else {
  25647. destination[path] = currentValue;
  25648. }
  25649. if (this._target.markAsDirty) {
  25650. this._target.markAsDirty(this.targetProperty);
  25651. }
  25652. };
  25653. Animation.prototype.goToFrame = function (frame) {
  25654. if (frame < this._keys[0].frame) {
  25655. frame = this._keys[0].frame;
  25656. }
  25657. else if (frame > this._keys[this._keys.length - 1].frame) {
  25658. frame = this._keys[this._keys.length - 1].frame;
  25659. }
  25660. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25661. this.setValue(currentValue);
  25662. };
  25663. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25664. if (blend === void 0) { blend = false; }
  25665. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25666. this._stopped = true;
  25667. return false;
  25668. }
  25669. var returnValue = true;
  25670. // Adding a start key at frame 0 if missing
  25671. if (this._keys[0].frame !== 0) {
  25672. var newKey = { frame: 0, value: this._keys[0].value };
  25673. this._keys.splice(0, 0, newKey);
  25674. }
  25675. // Check limits
  25676. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25677. from = this._keys[0].frame;
  25678. }
  25679. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25680. to = this._keys[this._keys.length - 1].frame;
  25681. }
  25682. // Compute ratio
  25683. var range = to - from;
  25684. var offsetValue;
  25685. // ratio represents the frame delta between from and to
  25686. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25687. var highLimitValue = 0;
  25688. if (ratio > range && !loop) {
  25689. returnValue = false;
  25690. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25691. }
  25692. else {
  25693. // Get max value if required
  25694. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25695. var keyOffset = to.toString() + from.toString();
  25696. if (!this._offsetsCache[keyOffset]) {
  25697. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25698. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25699. switch (this.dataType) {
  25700. // Float
  25701. case Animation.ANIMATIONTYPE_FLOAT:
  25702. this._offsetsCache[keyOffset] = toValue - fromValue;
  25703. break;
  25704. // Quaternion
  25705. case Animation.ANIMATIONTYPE_QUATERNION:
  25706. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25707. break;
  25708. // Vector3
  25709. case Animation.ANIMATIONTYPE_VECTOR3:
  25710. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25711. // Vector2
  25712. case Animation.ANIMATIONTYPE_VECTOR2:
  25713. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25714. // Color3
  25715. case Animation.ANIMATIONTYPE_COLOR3:
  25716. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25717. default:
  25718. break;
  25719. }
  25720. this._highLimitsCache[keyOffset] = toValue;
  25721. }
  25722. highLimitValue = this._highLimitsCache[keyOffset];
  25723. offsetValue = this._offsetsCache[keyOffset];
  25724. }
  25725. }
  25726. if (offsetValue === undefined) {
  25727. switch (this.dataType) {
  25728. // Float
  25729. case Animation.ANIMATIONTYPE_FLOAT:
  25730. offsetValue = 0;
  25731. break;
  25732. // Quaternion
  25733. case Animation.ANIMATIONTYPE_QUATERNION:
  25734. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25735. break;
  25736. // Vector3
  25737. case Animation.ANIMATIONTYPE_VECTOR3:
  25738. offsetValue = BABYLON.Vector3.Zero();
  25739. break;
  25740. // Vector2
  25741. case Animation.ANIMATIONTYPE_VECTOR2:
  25742. offsetValue = BABYLON.Vector2.Zero();
  25743. break;
  25744. // Color3
  25745. case Animation.ANIMATIONTYPE_COLOR3:
  25746. offsetValue = BABYLON.Color3.Black();
  25747. }
  25748. }
  25749. // Compute value
  25750. var repeatCount = (ratio / range) >> 0;
  25751. var currentFrame = returnValue ? from + ratio % range : to;
  25752. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25753. // Set value
  25754. this.setValue(currentValue);
  25755. // Check events
  25756. for (var index = 0; index < this._events.length; index++) {
  25757. if (currentFrame >= this._events[index].frame) {
  25758. var event = this._events[index];
  25759. if (!event.isDone) {
  25760. // If event should be done only once, remove it.
  25761. if (event.onlyOnce) {
  25762. this._events.splice(index, 1);
  25763. index--;
  25764. }
  25765. event.isDone = true;
  25766. event.action();
  25767. } // Don't do anything if the event has already be done.
  25768. }
  25769. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25770. // reset event, the animation is looping
  25771. this._events[index].isDone = false;
  25772. }
  25773. }
  25774. if (!returnValue) {
  25775. this._stopped = true;
  25776. }
  25777. return returnValue;
  25778. };
  25779. Animation.prototype.serialize = function () {
  25780. var serializationObject = {};
  25781. serializationObject.name = this.name;
  25782. serializationObject.property = this.targetProperty;
  25783. serializationObject.framePerSecond = this.framePerSecond;
  25784. serializationObject.dataType = this.dataType;
  25785. serializationObject.loopBehavior = this.loopMode;
  25786. var dataType = this.dataType;
  25787. serializationObject.keys = [];
  25788. var keys = this.getKeys();
  25789. for (var index = 0; index < keys.length; index++) {
  25790. var animationKey = keys[index];
  25791. var key = {};
  25792. key.frame = animationKey.frame;
  25793. switch (dataType) {
  25794. case Animation.ANIMATIONTYPE_FLOAT:
  25795. key.values = [animationKey.value];
  25796. break;
  25797. case Animation.ANIMATIONTYPE_QUATERNION:
  25798. case Animation.ANIMATIONTYPE_MATRIX:
  25799. case Animation.ANIMATIONTYPE_VECTOR3:
  25800. case Animation.ANIMATIONTYPE_COLOR3:
  25801. key.values = animationKey.value.asArray();
  25802. break;
  25803. }
  25804. serializationObject.keys.push(key);
  25805. }
  25806. serializationObject.ranges = [];
  25807. for (var name in this._ranges) {
  25808. var range = {};
  25809. range.name = name;
  25810. range.from = this._ranges[name].from;
  25811. range.to = this._ranges[name].to;
  25812. serializationObject.ranges.push(range);
  25813. }
  25814. return serializationObject;
  25815. };
  25816. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25817. get: function () {
  25818. return Animation._ANIMATIONTYPE_FLOAT;
  25819. },
  25820. enumerable: true,
  25821. configurable: true
  25822. });
  25823. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25824. get: function () {
  25825. return Animation._ANIMATIONTYPE_VECTOR3;
  25826. },
  25827. enumerable: true,
  25828. configurable: true
  25829. });
  25830. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25831. get: function () {
  25832. return Animation._ANIMATIONTYPE_VECTOR2;
  25833. },
  25834. enumerable: true,
  25835. configurable: true
  25836. });
  25837. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25838. get: function () {
  25839. return Animation._ANIMATIONTYPE_QUATERNION;
  25840. },
  25841. enumerable: true,
  25842. configurable: true
  25843. });
  25844. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25845. get: function () {
  25846. return Animation._ANIMATIONTYPE_MATRIX;
  25847. },
  25848. enumerable: true,
  25849. configurable: true
  25850. });
  25851. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25852. get: function () {
  25853. return Animation._ANIMATIONTYPE_COLOR3;
  25854. },
  25855. enumerable: true,
  25856. configurable: true
  25857. });
  25858. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25859. get: function () {
  25860. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25861. },
  25862. enumerable: true,
  25863. configurable: true
  25864. });
  25865. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25866. get: function () {
  25867. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25868. },
  25869. enumerable: true,
  25870. configurable: true
  25871. });
  25872. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25873. get: function () {
  25874. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. Animation.Parse = function (parsedAnimation) {
  25880. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25881. var dataType = parsedAnimation.dataType;
  25882. var keys = [];
  25883. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25884. var key = parsedAnimation.keys[index];
  25885. var data;
  25886. switch (dataType) {
  25887. case Animation.ANIMATIONTYPE_FLOAT:
  25888. data = key.values[0];
  25889. break;
  25890. case Animation.ANIMATIONTYPE_QUATERNION:
  25891. data = BABYLON.Quaternion.FromArray(key.values);
  25892. break;
  25893. case Animation.ANIMATIONTYPE_MATRIX:
  25894. data = BABYLON.Matrix.FromArray(key.values);
  25895. break;
  25896. case Animation.ANIMATIONTYPE_COLOR3:
  25897. data = BABYLON.Color3.FromArray(key.values);
  25898. break;
  25899. case Animation.ANIMATIONTYPE_VECTOR3:
  25900. default:
  25901. data = BABYLON.Vector3.FromArray(key.values);
  25902. break;
  25903. }
  25904. keys.push({
  25905. frame: key.frame,
  25906. value: data
  25907. });
  25908. }
  25909. animation.setKeys(keys);
  25910. if (parsedAnimation.ranges) {
  25911. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25912. data = parsedAnimation.ranges[index];
  25913. animation.createRange(data.name, data.from, data.to);
  25914. }
  25915. }
  25916. return animation;
  25917. };
  25918. Animation.AppendSerializedAnimations = function (source, destination) {
  25919. if (source.animations) {
  25920. destination.animations = [];
  25921. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25922. var animation = source.animations[animationIndex];
  25923. destination.animations.push(animation.serialize());
  25924. }
  25925. }
  25926. };
  25927. // Statics
  25928. Animation._ANIMATIONTYPE_FLOAT = 0;
  25929. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25930. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25931. Animation._ANIMATIONTYPE_MATRIX = 3;
  25932. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25933. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25934. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25935. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25936. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25937. return Animation;
  25938. })();
  25939. BABYLON.Animation = Animation;
  25940. })(BABYLON || (BABYLON = {}));
  25941. var BABYLON;
  25942. (function (BABYLON) {
  25943. var Animatable = (function () {
  25944. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25945. if (fromFrame === void 0) { fromFrame = 0; }
  25946. if (toFrame === void 0) { toFrame = 100; }
  25947. if (loopAnimation === void 0) { loopAnimation = false; }
  25948. if (speedRatio === void 0) { speedRatio = 1.0; }
  25949. this.target = target;
  25950. this.fromFrame = fromFrame;
  25951. this.toFrame = toFrame;
  25952. this.loopAnimation = loopAnimation;
  25953. this.speedRatio = speedRatio;
  25954. this.onAnimationEnd = onAnimationEnd;
  25955. this._animations = new Array();
  25956. this._paused = false;
  25957. this.animationStarted = false;
  25958. if (animations) {
  25959. this.appendAnimations(target, animations);
  25960. }
  25961. this._scene = scene;
  25962. scene._activeAnimatables.push(this);
  25963. }
  25964. // Methods
  25965. Animatable.prototype.getAnimations = function () {
  25966. return this._animations;
  25967. };
  25968. Animatable.prototype.appendAnimations = function (target, animations) {
  25969. for (var index = 0; index < animations.length; index++) {
  25970. var animation = animations[index];
  25971. animation._target = target;
  25972. this._animations.push(animation);
  25973. }
  25974. };
  25975. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25976. var animations = this._animations;
  25977. for (var index = 0; index < animations.length; index++) {
  25978. if (animations[index].targetProperty === property) {
  25979. return animations[index];
  25980. }
  25981. }
  25982. return null;
  25983. };
  25984. Animatable.prototype.reset = function () {
  25985. var animations = this._animations;
  25986. for (var index = 0; index < animations.length; index++) {
  25987. animations[index].reset();
  25988. }
  25989. this._localDelayOffset = null;
  25990. this._pausedDelay = null;
  25991. };
  25992. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25993. var animations = this._animations;
  25994. for (var index = 0; index < animations.length; index++) {
  25995. animations[index].enableBlending = true;
  25996. animations[index].blendingSpeed = blendingSpeed;
  25997. }
  25998. };
  25999. Animatable.prototype.disableBlending = function () {
  26000. var animations = this._animations;
  26001. for (var index = 0; index < animations.length; index++) {
  26002. animations[index].enableBlending = false;
  26003. }
  26004. };
  26005. Animatable.prototype.goToFrame = function (frame) {
  26006. var animations = this._animations;
  26007. for (var index = 0; index < animations.length; index++) {
  26008. animations[index].goToFrame(frame);
  26009. }
  26010. };
  26011. Animatable.prototype.pause = function () {
  26012. if (this._paused) {
  26013. return;
  26014. }
  26015. this._paused = true;
  26016. };
  26017. Animatable.prototype.restart = function () {
  26018. this._paused = false;
  26019. };
  26020. Animatable.prototype.stop = function () {
  26021. var index = this._scene._activeAnimatables.indexOf(this);
  26022. if (index > -1) {
  26023. this._scene._activeAnimatables.splice(index, 1);
  26024. var animations = this._animations;
  26025. for (var index = 0; index < animations.length; index++) {
  26026. animations[index].reset();
  26027. }
  26028. if (this.onAnimationEnd) {
  26029. this.onAnimationEnd();
  26030. }
  26031. }
  26032. };
  26033. Animatable.prototype._animate = function (delay) {
  26034. if (this._paused) {
  26035. this.animationStarted = false;
  26036. if (!this._pausedDelay) {
  26037. this._pausedDelay = delay;
  26038. }
  26039. return true;
  26040. }
  26041. if (!this._localDelayOffset) {
  26042. this._localDelayOffset = delay;
  26043. }
  26044. else if (this._pausedDelay) {
  26045. this._localDelayOffset += delay - this._pausedDelay;
  26046. this._pausedDelay = null;
  26047. }
  26048. // Animating
  26049. var running = false;
  26050. var animations = this._animations;
  26051. var index;
  26052. for (index = 0; index < animations.length; index++) {
  26053. var animation = animations[index];
  26054. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  26055. running = running || isRunning;
  26056. }
  26057. this.animationStarted = running;
  26058. if (!running) {
  26059. // Remove from active animatables
  26060. index = this._scene._activeAnimatables.indexOf(this);
  26061. this._scene._activeAnimatables.splice(index, 1);
  26062. }
  26063. if (!running && this.onAnimationEnd) {
  26064. this.onAnimationEnd();
  26065. this.onAnimationEnd = null;
  26066. }
  26067. return running;
  26068. };
  26069. return Animatable;
  26070. })();
  26071. BABYLON.Animatable = Animatable;
  26072. })(BABYLON || (BABYLON = {}));
  26073. var BABYLON;
  26074. (function (BABYLON) {
  26075. var EasingFunction = (function () {
  26076. function EasingFunction() {
  26077. // Properties
  26078. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  26079. }
  26080. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  26081. get: function () {
  26082. return EasingFunction._EASINGMODE_EASEIN;
  26083. },
  26084. enumerable: true,
  26085. configurable: true
  26086. });
  26087. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  26088. get: function () {
  26089. return EasingFunction._EASINGMODE_EASEOUT;
  26090. },
  26091. enumerable: true,
  26092. configurable: true
  26093. });
  26094. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  26095. get: function () {
  26096. return EasingFunction._EASINGMODE_EASEINOUT;
  26097. },
  26098. enumerable: true,
  26099. configurable: true
  26100. });
  26101. EasingFunction.prototype.setEasingMode = function (easingMode) {
  26102. var n = Math.min(Math.max(easingMode, 0), 2);
  26103. this._easingMode = n;
  26104. };
  26105. EasingFunction.prototype.getEasingMode = function () {
  26106. return this._easingMode;
  26107. };
  26108. EasingFunction.prototype.easeInCore = function (gradient) {
  26109. throw new Error('You must implement this method');
  26110. };
  26111. EasingFunction.prototype.ease = function (gradient) {
  26112. switch (this._easingMode) {
  26113. case EasingFunction.EASINGMODE_EASEIN:
  26114. return this.easeInCore(gradient);
  26115. case EasingFunction.EASINGMODE_EASEOUT:
  26116. return (1 - this.easeInCore(1 - gradient));
  26117. }
  26118. if (gradient >= 0.5) {
  26119. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  26120. }
  26121. return (this.easeInCore(gradient * 2) * 0.5);
  26122. };
  26123. //Statics
  26124. EasingFunction._EASINGMODE_EASEIN = 0;
  26125. EasingFunction._EASINGMODE_EASEOUT = 1;
  26126. EasingFunction._EASINGMODE_EASEINOUT = 2;
  26127. return EasingFunction;
  26128. })();
  26129. BABYLON.EasingFunction = EasingFunction;
  26130. var CircleEase = (function (_super) {
  26131. __extends(CircleEase, _super);
  26132. function CircleEase() {
  26133. _super.apply(this, arguments);
  26134. }
  26135. CircleEase.prototype.easeInCore = function (gradient) {
  26136. gradient = Math.max(0, Math.min(1, gradient));
  26137. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  26138. };
  26139. return CircleEase;
  26140. })(EasingFunction);
  26141. BABYLON.CircleEase = CircleEase;
  26142. var BackEase = (function (_super) {
  26143. __extends(BackEase, _super);
  26144. function BackEase(amplitude) {
  26145. if (amplitude === void 0) { amplitude = 1; }
  26146. _super.call(this);
  26147. this.amplitude = amplitude;
  26148. }
  26149. BackEase.prototype.easeInCore = function (gradient) {
  26150. var num = Math.max(0, this.amplitude);
  26151. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  26152. };
  26153. return BackEase;
  26154. })(EasingFunction);
  26155. BABYLON.BackEase = BackEase;
  26156. var BounceEase = (function (_super) {
  26157. __extends(BounceEase, _super);
  26158. function BounceEase(bounces, bounciness) {
  26159. if (bounces === void 0) { bounces = 3; }
  26160. if (bounciness === void 0) { bounciness = 2; }
  26161. _super.call(this);
  26162. this.bounces = bounces;
  26163. this.bounciness = bounciness;
  26164. }
  26165. BounceEase.prototype.easeInCore = function (gradient) {
  26166. var y = Math.max(0.0, this.bounces);
  26167. var bounciness = this.bounciness;
  26168. if (bounciness <= 1.0) {
  26169. bounciness = 1.001;
  26170. }
  26171. var num9 = Math.pow(bounciness, y);
  26172. var num5 = 1.0 - bounciness;
  26173. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  26174. var num15 = gradient * num4;
  26175. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  26176. var num3 = Math.floor(num65);
  26177. var num13 = num3 + 1.0;
  26178. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  26179. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  26180. var num7 = (num8 + num12) * 0.5;
  26181. var num6 = gradient - num7;
  26182. var num2 = num7 - num8;
  26183. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  26184. };
  26185. return BounceEase;
  26186. })(EasingFunction);
  26187. BABYLON.BounceEase = BounceEase;
  26188. var CubicEase = (function (_super) {
  26189. __extends(CubicEase, _super);
  26190. function CubicEase() {
  26191. _super.apply(this, arguments);
  26192. }
  26193. CubicEase.prototype.easeInCore = function (gradient) {
  26194. return (gradient * gradient * gradient);
  26195. };
  26196. return CubicEase;
  26197. })(EasingFunction);
  26198. BABYLON.CubicEase = CubicEase;
  26199. var ElasticEase = (function (_super) {
  26200. __extends(ElasticEase, _super);
  26201. function ElasticEase(oscillations, springiness) {
  26202. if (oscillations === void 0) { oscillations = 3; }
  26203. if (springiness === void 0) { springiness = 3; }
  26204. _super.call(this);
  26205. this.oscillations = oscillations;
  26206. this.springiness = springiness;
  26207. }
  26208. ElasticEase.prototype.easeInCore = function (gradient) {
  26209. var num2;
  26210. var num3 = Math.max(0.0, this.oscillations);
  26211. var num = Math.max(0.0, this.springiness);
  26212. if (num == 0) {
  26213. num2 = gradient;
  26214. }
  26215. else {
  26216. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  26217. }
  26218. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  26219. };
  26220. return ElasticEase;
  26221. })(EasingFunction);
  26222. BABYLON.ElasticEase = ElasticEase;
  26223. var ExponentialEase = (function (_super) {
  26224. __extends(ExponentialEase, _super);
  26225. function ExponentialEase(exponent) {
  26226. if (exponent === void 0) { exponent = 2; }
  26227. _super.call(this);
  26228. this.exponent = exponent;
  26229. }
  26230. ExponentialEase.prototype.easeInCore = function (gradient) {
  26231. if (this.exponent <= 0) {
  26232. return gradient;
  26233. }
  26234. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  26235. };
  26236. return ExponentialEase;
  26237. })(EasingFunction);
  26238. BABYLON.ExponentialEase = ExponentialEase;
  26239. var PowerEase = (function (_super) {
  26240. __extends(PowerEase, _super);
  26241. function PowerEase(power) {
  26242. if (power === void 0) { power = 2; }
  26243. _super.call(this);
  26244. this.power = power;
  26245. }
  26246. PowerEase.prototype.easeInCore = function (gradient) {
  26247. var y = Math.max(0.0, this.power);
  26248. return Math.pow(gradient, y);
  26249. };
  26250. return PowerEase;
  26251. })(EasingFunction);
  26252. BABYLON.PowerEase = PowerEase;
  26253. var QuadraticEase = (function (_super) {
  26254. __extends(QuadraticEase, _super);
  26255. function QuadraticEase() {
  26256. _super.apply(this, arguments);
  26257. }
  26258. QuadraticEase.prototype.easeInCore = function (gradient) {
  26259. return (gradient * gradient);
  26260. };
  26261. return QuadraticEase;
  26262. })(EasingFunction);
  26263. BABYLON.QuadraticEase = QuadraticEase;
  26264. var QuarticEase = (function (_super) {
  26265. __extends(QuarticEase, _super);
  26266. function QuarticEase() {
  26267. _super.apply(this, arguments);
  26268. }
  26269. QuarticEase.prototype.easeInCore = function (gradient) {
  26270. return (gradient * gradient * gradient * gradient);
  26271. };
  26272. return QuarticEase;
  26273. })(EasingFunction);
  26274. BABYLON.QuarticEase = QuarticEase;
  26275. var QuinticEase = (function (_super) {
  26276. __extends(QuinticEase, _super);
  26277. function QuinticEase() {
  26278. _super.apply(this, arguments);
  26279. }
  26280. QuinticEase.prototype.easeInCore = function (gradient) {
  26281. return (gradient * gradient * gradient * gradient * gradient);
  26282. };
  26283. return QuinticEase;
  26284. })(EasingFunction);
  26285. BABYLON.QuinticEase = QuinticEase;
  26286. var SineEase = (function (_super) {
  26287. __extends(SineEase, _super);
  26288. function SineEase() {
  26289. _super.apply(this, arguments);
  26290. }
  26291. SineEase.prototype.easeInCore = function (gradient) {
  26292. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26293. };
  26294. return SineEase;
  26295. })(EasingFunction);
  26296. BABYLON.SineEase = SineEase;
  26297. var BezierCurveEase = (function (_super) {
  26298. __extends(BezierCurveEase, _super);
  26299. function BezierCurveEase(x1, y1, x2, y2) {
  26300. if (x1 === void 0) { x1 = 0; }
  26301. if (y1 === void 0) { y1 = 0; }
  26302. if (x2 === void 0) { x2 = 1; }
  26303. if (y2 === void 0) { y2 = 1; }
  26304. _super.call(this);
  26305. this.x1 = x1;
  26306. this.y1 = y1;
  26307. this.x2 = x2;
  26308. this.y2 = y2;
  26309. }
  26310. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26311. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26312. };
  26313. return BezierCurveEase;
  26314. })(EasingFunction);
  26315. BABYLON.BezierCurveEase = BezierCurveEase;
  26316. })(BABYLON || (BABYLON = {}));
  26317. var BABYLON;
  26318. (function (BABYLON) {
  26319. var Bone = (function (_super) {
  26320. __extends(Bone, _super);
  26321. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26322. _super.call(this, name, skeleton.getScene());
  26323. this.name = name;
  26324. this.children = new Array();
  26325. this.animations = new Array();
  26326. this._worldTransform = new BABYLON.Matrix();
  26327. this._absoluteTransform = new BABYLON.Matrix();
  26328. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26329. this._skeleton = skeleton;
  26330. this._matrix = matrix;
  26331. this._baseMatrix = matrix;
  26332. this._restPose = restPose ? restPose : matrix.clone();
  26333. skeleton.bones.push(this);
  26334. if (parentBone) {
  26335. this._parent = parentBone;
  26336. parentBone.children.push(this);
  26337. }
  26338. else {
  26339. this._parent = null;
  26340. }
  26341. this._updateDifferenceMatrix();
  26342. }
  26343. // Members
  26344. Bone.prototype.getParent = function () {
  26345. return this._parent;
  26346. };
  26347. Bone.prototype.getLocalMatrix = function () {
  26348. return this._matrix;
  26349. };
  26350. Bone.prototype.getBaseMatrix = function () {
  26351. return this._baseMatrix;
  26352. };
  26353. Bone.prototype.getRestPose = function () {
  26354. return this._restPose;
  26355. };
  26356. Bone.prototype.returnToRest = function () {
  26357. this.updateMatrix(this._restPose.clone());
  26358. };
  26359. Bone.prototype.getWorldMatrix = function () {
  26360. return this._worldTransform;
  26361. };
  26362. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26363. return this._invertedAbsoluteTransform;
  26364. };
  26365. Bone.prototype.getAbsoluteTransform = function () {
  26366. return this._absoluteTransform;
  26367. };
  26368. // Methods
  26369. Bone.prototype.updateMatrix = function (matrix) {
  26370. this._baseMatrix = matrix.clone();
  26371. this._matrix = matrix.clone();
  26372. this._skeleton._markAsDirty();
  26373. this._updateDifferenceMatrix();
  26374. };
  26375. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26376. if (!rootMatrix) {
  26377. rootMatrix = this._baseMatrix;
  26378. }
  26379. if (this._parent) {
  26380. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26381. }
  26382. else {
  26383. this._absoluteTransform.copyFrom(rootMatrix);
  26384. }
  26385. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26386. for (var index = 0; index < this.children.length; index++) {
  26387. this.children[index]._updateDifferenceMatrix();
  26388. }
  26389. };
  26390. Bone.prototype.markAsDirty = function () {
  26391. this._currentRenderId++;
  26392. this._skeleton._markAsDirty();
  26393. };
  26394. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26395. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26396. // all animation may be coming from a library skeleton, so may need to create animation
  26397. if (this.animations.length === 0) {
  26398. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26399. this.animations[0].setKeys([]);
  26400. }
  26401. // get animation info / verify there is such a range from the source bone
  26402. var sourceRange = source.animations[0].getRange(rangeName);
  26403. if (!sourceRange) {
  26404. return false;
  26405. }
  26406. var from = sourceRange.from;
  26407. var to = sourceRange.to;
  26408. var sourceKeys = source.animations[0].getKeys();
  26409. // rescaling prep
  26410. var sourceBoneLength = source.length;
  26411. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26412. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26413. var destKeys = this.animations[0].getKeys();
  26414. // loop vars declaration / initialization
  26415. var orig;
  26416. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26417. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26418. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26419. var mat;
  26420. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26421. orig = sourceKeys[key];
  26422. if (orig.frame >= from && orig.frame <= to) {
  26423. if (scalingReqd) {
  26424. orig.value.decompose(origScale, origRotation, origTranslation);
  26425. origTranslation.scaleInPlace(ratio);
  26426. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26427. }
  26428. else {
  26429. mat = orig.value;
  26430. }
  26431. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26432. }
  26433. }
  26434. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26435. return true;
  26436. };
  26437. return Bone;
  26438. })(BABYLON.Node);
  26439. BABYLON.Bone = Bone;
  26440. })(BABYLON || (BABYLON = {}));
  26441. var BABYLON;
  26442. (function (BABYLON) {
  26443. var Skeleton = (function () {
  26444. function Skeleton(name, id, scene) {
  26445. this.name = name;
  26446. this.id = id;
  26447. this.bones = new Array();
  26448. this.needInitialSkinMatrix = false;
  26449. this._isDirty = true;
  26450. this._meshesWithPoseMatrix = new Array();
  26451. this._identity = BABYLON.Matrix.Identity();
  26452. this._ranges = {};
  26453. this.bones = [];
  26454. this._scene = scene;
  26455. scene.skeletons.push(this);
  26456. //make sure it will recalculate the matrix next time prepare is called.
  26457. this._isDirty = true;
  26458. }
  26459. // Members
  26460. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26461. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26462. return mesh._bonesTransformMatrices;
  26463. }
  26464. return this._transformMatrices;
  26465. };
  26466. Skeleton.prototype.getScene = function () {
  26467. return this._scene;
  26468. };
  26469. // Methods
  26470. /**
  26471. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26472. */
  26473. Skeleton.prototype.toString = function (fullDetails) {
  26474. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26475. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26476. if (fullDetails) {
  26477. ret += ", Ranges: {";
  26478. var first = true;
  26479. for (var name in this._ranges) {
  26480. if (!first) {
  26481. ret + ", ";
  26482. first = false;
  26483. }
  26484. ret += name;
  26485. }
  26486. ret += "}";
  26487. }
  26488. return ret;
  26489. };
  26490. /**
  26491. * Get bone's index searching by name
  26492. * @param {string} name is bone's name to search for
  26493. * @return {number} Indice of the bone. Returns -1 if not found
  26494. */
  26495. Skeleton.prototype.getBoneIndexByName = function (name) {
  26496. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26497. if (this.bones[boneIndex].name === name) {
  26498. return boneIndex;
  26499. }
  26500. }
  26501. return -1;
  26502. };
  26503. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26504. // check name not already in use
  26505. if (!this._ranges[name]) {
  26506. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26507. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26508. if (this.bones[i].animations[0]) {
  26509. this.bones[i].animations[0].createRange(name, from, to);
  26510. }
  26511. }
  26512. }
  26513. };
  26514. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26515. if (deleteFrames === void 0) { deleteFrames = true; }
  26516. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26517. if (this.bones[i].animations[0]) {
  26518. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26519. }
  26520. }
  26521. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26522. };
  26523. Skeleton.prototype.getAnimationRange = function (name) {
  26524. return this._ranges[name];
  26525. };
  26526. /**
  26527. * Returns as an Array, all AnimationRanges defined on this skeleton
  26528. */
  26529. Skeleton.prototype.getAnimationRanges = function () {
  26530. var animationRanges = [];
  26531. var name;
  26532. var i = 0;
  26533. for (name in this._ranges) {
  26534. animationRanges[i] = this._ranges[name];
  26535. i++;
  26536. }
  26537. return animationRanges;
  26538. };
  26539. /**
  26540. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26541. */
  26542. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26543. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26544. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26545. return false;
  26546. }
  26547. var ret = true;
  26548. var frameOffset = this._getHighestAnimationFrame() + 1;
  26549. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26550. var boneDict = {};
  26551. var sourceBones = source.bones;
  26552. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26553. boneDict[sourceBones[i].name] = sourceBones[i];
  26554. }
  26555. if (this.bones.length !== sourceBones.length) {
  26556. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26557. ret = false;
  26558. }
  26559. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26560. var boneName = this.bones[i].name;
  26561. var sourceBone = boneDict[boneName];
  26562. if (sourceBone) {
  26563. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26564. }
  26565. else {
  26566. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26567. ret = false;
  26568. }
  26569. }
  26570. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26571. var range = source.getAnimationRange(name);
  26572. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26573. return ret;
  26574. };
  26575. Skeleton.prototype.returnToRest = function () {
  26576. for (var index = 0; index < this.bones.length; index++) {
  26577. this.bones[index].returnToRest();
  26578. }
  26579. };
  26580. Skeleton.prototype._getHighestAnimationFrame = function () {
  26581. var ret = 0;
  26582. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26583. if (this.bones[i].animations[0]) {
  26584. var highest = this.bones[i].animations[0].getHighestFrame();
  26585. if (ret < highest) {
  26586. ret = highest;
  26587. }
  26588. }
  26589. }
  26590. return ret;
  26591. };
  26592. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26593. var range = this.getAnimationRange(name);
  26594. if (!range) {
  26595. return null;
  26596. }
  26597. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26598. };
  26599. Skeleton.prototype._markAsDirty = function () {
  26600. this._isDirty = true;
  26601. };
  26602. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26603. this._meshesWithPoseMatrix.push(mesh);
  26604. };
  26605. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26606. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26607. if (index > -1) {
  26608. this._meshesWithPoseMatrix.splice(index, 1);
  26609. }
  26610. };
  26611. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26612. for (var index = 0; index < this.bones.length; index++) {
  26613. var bone = this.bones[index];
  26614. var parentBone = bone.getParent();
  26615. if (parentBone) {
  26616. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26617. }
  26618. else {
  26619. if (initialSkinMatrix) {
  26620. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26621. }
  26622. else {
  26623. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26624. }
  26625. }
  26626. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26627. }
  26628. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26629. };
  26630. Skeleton.prototype.prepare = function () {
  26631. if (!this._isDirty) {
  26632. return;
  26633. }
  26634. if (this.needInitialSkinMatrix) {
  26635. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26636. var mesh = this._meshesWithPoseMatrix[index];
  26637. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26638. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26639. }
  26640. var poseMatrix = mesh.getPoseMatrix();
  26641. // Prepare bones
  26642. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26643. var bone = this.bones[boneIndex];
  26644. if (!bone.getParent()) {
  26645. var matrix = bone.getBaseMatrix();
  26646. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26647. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26648. }
  26649. }
  26650. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26651. }
  26652. }
  26653. else {
  26654. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26655. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26656. }
  26657. this._computeTransformMatrices(this._transformMatrices, null);
  26658. }
  26659. this._isDirty = false;
  26660. this._scene._activeBones += this.bones.length;
  26661. };
  26662. Skeleton.prototype.getAnimatables = function () {
  26663. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26664. this._animatables = [];
  26665. for (var index = 0; index < this.bones.length; index++) {
  26666. this._animatables.push(this.bones[index]);
  26667. }
  26668. }
  26669. return this._animatables;
  26670. };
  26671. Skeleton.prototype.clone = function (name, id) {
  26672. var result = new Skeleton(name, id || name, this._scene);
  26673. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26674. for (var index = 0; index < this.bones.length; index++) {
  26675. var source = this.bones[index];
  26676. var parentBone = null;
  26677. if (source.getParent()) {
  26678. var parentIndex = this.bones.indexOf(source.getParent());
  26679. parentBone = result.bones[parentIndex];
  26680. }
  26681. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26682. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26683. }
  26684. if (this._ranges) {
  26685. result._ranges = {};
  26686. for (var rangeName in this._ranges) {
  26687. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26688. }
  26689. }
  26690. this._isDirty = true;
  26691. return result;
  26692. };
  26693. Skeleton.prototype.dispose = function () {
  26694. this._meshesWithPoseMatrix = [];
  26695. // Animations
  26696. this.getScene().stopAnimation(this);
  26697. // Remove from scene
  26698. this.getScene().removeSkeleton(this);
  26699. };
  26700. Skeleton.prototype.serialize = function () {
  26701. var serializationObject = {};
  26702. serializationObject.name = this.name;
  26703. serializationObject.id = this.id;
  26704. serializationObject.bones = [];
  26705. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26706. for (var index = 0; index < this.bones.length; index++) {
  26707. var bone = this.bones[index];
  26708. var serializedBone = {
  26709. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26710. name: bone.name,
  26711. matrix: bone.getLocalMatrix().toArray(),
  26712. rest: bone.getRestPose().toArray()
  26713. };
  26714. serializationObject.bones.push(serializedBone);
  26715. if (bone.length) {
  26716. serializedBone.length = bone.length;
  26717. }
  26718. if (bone.animations && bone.animations.length > 0) {
  26719. serializedBone.animation = bone.animations[0].serialize();
  26720. }
  26721. serializationObject.ranges = [];
  26722. for (var name in this._ranges) {
  26723. var range = {};
  26724. range.name = name;
  26725. range.from = this._ranges[name].from;
  26726. range.to = this._ranges[name].to;
  26727. serializationObject.ranges.push(range);
  26728. }
  26729. }
  26730. return serializationObject;
  26731. };
  26732. Skeleton.Parse = function (parsedSkeleton, scene) {
  26733. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26734. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26735. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26736. var parsedBone = parsedSkeleton.bones[index];
  26737. var parentBone = null;
  26738. if (parsedBone.parentBoneIndex > -1) {
  26739. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26740. }
  26741. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26742. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26743. if (parsedBone.length) {
  26744. bone.length = parsedBone.length;
  26745. }
  26746. if (parsedBone.animation) {
  26747. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26748. }
  26749. }
  26750. // placed after bones, so createAnimationRange can cascade down
  26751. if (parsedSkeleton.ranges) {
  26752. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26753. var data = parsedSkeleton.ranges[index];
  26754. skeleton.createAnimationRange(data.name, data.from, data.to);
  26755. }
  26756. }
  26757. return skeleton;
  26758. };
  26759. return Skeleton;
  26760. })();
  26761. BABYLON.Skeleton = Skeleton;
  26762. })(BABYLON || (BABYLON = {}));
  26763. var BABYLON;
  26764. (function (BABYLON) {
  26765. var PostProcess = (function () {
  26766. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26768. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26769. this.name = name;
  26770. this.width = -1;
  26771. this.height = -1;
  26772. /*
  26773. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  26774. Can only be used on a single postprocess or on the last one of a chain.
  26775. */
  26776. this.enablePixelPerfectMode = false;
  26777. this._reusable = false;
  26778. this._textures = new BABYLON.SmartArray(2);
  26779. this._currentRenderTextureInd = 0;
  26780. this._scaleRatio = new BABYLON.Vector2(1, 1);
  26781. if (camera != null) {
  26782. this._camera = camera;
  26783. this._scene = camera.getScene();
  26784. camera.attachPostProcess(this);
  26785. this._engine = this._scene.getEngine();
  26786. }
  26787. else {
  26788. this._engine = engine;
  26789. }
  26790. this._renderRatio = ratio;
  26791. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26792. this._reusable = reusable || false;
  26793. this._textureType = textureType;
  26794. this._samplers = samplers || [];
  26795. this._samplers.push("textureSampler");
  26796. this._fragmentUrl = fragmentUrl;
  26797. this._parameters = parameters || [];
  26798. this._parameters.push("scale");
  26799. this.updateEffect(defines);
  26800. }
  26801. PostProcess.prototype.updateEffect = function (defines) {
  26802. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26803. };
  26804. PostProcess.prototype.isReusable = function () {
  26805. return this._reusable;
  26806. };
  26807. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26808. camera = camera || this._camera;
  26809. var scene = camera.getScene();
  26810. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26811. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26812. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26813. var desiredWidth = this._renderRatio.width || requiredWidth;
  26814. var desiredHeight = this._renderRatio.height || requiredHeight;
  26815. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  26816. if (!this._renderRatio.width) {
  26817. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26818. }
  26819. if (!this._renderRatio.height) {
  26820. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26821. }
  26822. }
  26823. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26824. if (this._textures.length > 0) {
  26825. for (var i = 0; i < this._textures.length; i++) {
  26826. this._engine._releaseTexture(this._textures.data[i]);
  26827. }
  26828. this._textures.reset();
  26829. }
  26830. this.width = desiredWidth;
  26831. this.height = desiredHeight;
  26832. 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 }));
  26833. if (this._reusable) {
  26834. 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 }));
  26835. }
  26836. if (this.onSizeChanged) {
  26837. this.onSizeChanged();
  26838. }
  26839. }
  26840. if (this.enablePixelPerfectMode) {
  26841. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  26842. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  26843. }
  26844. else {
  26845. this._scaleRatio.copyFromFloats(1, 1);
  26846. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26847. }
  26848. if (this.onActivate) {
  26849. this.onActivate(camera);
  26850. }
  26851. // Clear
  26852. if (this.clearColor) {
  26853. this._engine.clear(this.clearColor, true, true);
  26854. }
  26855. else {
  26856. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26857. }
  26858. if (this._reusable) {
  26859. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26860. }
  26861. };
  26862. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26863. get: function () {
  26864. return this._effect.isSupported;
  26865. },
  26866. enumerable: true,
  26867. configurable: true
  26868. });
  26869. PostProcess.prototype.apply = function () {
  26870. // Check
  26871. if (!this._effect.isReady())
  26872. return null;
  26873. // States
  26874. this._engine.enableEffect(this._effect);
  26875. this._engine.setState(false);
  26876. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26877. this._engine.setDepthBuffer(false);
  26878. this._engine.setDepthWrite(false);
  26879. // Texture
  26880. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26881. // Parameters
  26882. this._effect.setVector2("scale", this._scaleRatio);
  26883. if (this.onApply) {
  26884. this.onApply(this._effect);
  26885. }
  26886. return this._effect;
  26887. };
  26888. PostProcess.prototype.dispose = function (camera) {
  26889. camera = camera || this._camera;
  26890. if (this._textures.length > 0) {
  26891. for (var i = 0; i < this._textures.length; i++) {
  26892. this._engine._releaseTexture(this._textures.data[i]);
  26893. }
  26894. this._textures.reset();
  26895. }
  26896. if (!camera) {
  26897. return;
  26898. }
  26899. camera.detachPostProcess(this);
  26900. var index = camera._postProcesses.indexOf(this);
  26901. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26902. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26903. }
  26904. };
  26905. return PostProcess;
  26906. })();
  26907. BABYLON.PostProcess = PostProcess;
  26908. })(BABYLON || (BABYLON = {}));
  26909. var BABYLON;
  26910. (function (BABYLON) {
  26911. var PostProcessManager = (function () {
  26912. function PostProcessManager(scene) {
  26913. this._vertexDeclaration = [2];
  26914. this._vertexStrideSize = 2 * 4;
  26915. this._scene = scene;
  26916. }
  26917. PostProcessManager.prototype._prepareBuffers = function () {
  26918. if (this._vertexBuffer) {
  26919. return;
  26920. }
  26921. // VBO
  26922. var vertices = [];
  26923. vertices.push(1, 1);
  26924. vertices.push(-1, 1);
  26925. vertices.push(-1, -1);
  26926. vertices.push(1, -1);
  26927. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26928. // Indices
  26929. var indices = [];
  26930. indices.push(0);
  26931. indices.push(1);
  26932. indices.push(2);
  26933. indices.push(0);
  26934. indices.push(2);
  26935. indices.push(3);
  26936. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26937. };
  26938. // Methods
  26939. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26940. var postProcesses = this._scene.activeCamera._postProcesses;
  26941. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26942. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26943. return false;
  26944. }
  26945. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26946. return true;
  26947. };
  26948. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26949. var engine = this._scene.getEngine();
  26950. for (var index = 0; index < postProcesses.length; index++) {
  26951. if (index < postProcesses.length - 1) {
  26952. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26953. }
  26954. else {
  26955. if (targetTexture) {
  26956. engine.bindFramebuffer(targetTexture);
  26957. }
  26958. else {
  26959. engine.restoreDefaultFramebuffer();
  26960. }
  26961. }
  26962. var pp = postProcesses[index];
  26963. var effect = pp.apply();
  26964. if (effect) {
  26965. if (pp.onBeforeRender) {
  26966. pp.onBeforeRender(effect);
  26967. }
  26968. // VBOs
  26969. this._prepareBuffers();
  26970. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26971. // Draw order
  26972. engine.draw(true, 0, 6);
  26973. if (pp.onAfterRender) {
  26974. pp.onAfterRender(effect);
  26975. }
  26976. }
  26977. }
  26978. // Restore depth buffer
  26979. engine.setDepthBuffer(true);
  26980. engine.setDepthWrite(true);
  26981. };
  26982. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26983. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26984. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26985. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26986. return;
  26987. }
  26988. var engine = this._scene.getEngine();
  26989. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26990. if (index < postProcessesTakenIndices.length - 1) {
  26991. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26992. }
  26993. else {
  26994. if (targetTexture) {
  26995. engine.bindFramebuffer(targetTexture, faceIndex);
  26996. }
  26997. else {
  26998. engine.restoreDefaultFramebuffer();
  26999. }
  27000. }
  27001. if (doNotPresent) {
  27002. break;
  27003. }
  27004. var pp = postProcesses[postProcessesTakenIndices[index]];
  27005. var effect = pp.apply();
  27006. if (effect) {
  27007. if (pp.onBeforeRender) {
  27008. pp.onBeforeRender(effect);
  27009. }
  27010. // VBOs
  27011. this._prepareBuffers();
  27012. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  27013. // Draw order
  27014. engine.draw(true, 0, 6);
  27015. if (pp.onAfterRender) {
  27016. pp.onAfterRender(effect);
  27017. }
  27018. }
  27019. }
  27020. // Restore depth buffer
  27021. engine.setDepthBuffer(true);
  27022. engine.setDepthWrite(true);
  27023. };
  27024. PostProcessManager.prototype.dispose = function () {
  27025. if (this._vertexBuffer) {
  27026. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  27027. this._vertexBuffer = null;
  27028. }
  27029. if (this._indexBuffer) {
  27030. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27031. this._indexBuffer = null;
  27032. }
  27033. };
  27034. return PostProcessManager;
  27035. })();
  27036. BABYLON.PostProcessManager = PostProcessManager;
  27037. })(BABYLON || (BABYLON = {}));
  27038. var BABYLON;
  27039. (function (BABYLON) {
  27040. var PassPostProcess = (function (_super) {
  27041. __extends(PassPostProcess, _super);
  27042. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27043. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  27044. }
  27045. return PassPostProcess;
  27046. })(BABYLON.PostProcess);
  27047. BABYLON.PassPostProcess = PassPostProcess;
  27048. })(BABYLON || (BABYLON = {}));
  27049. var BABYLON;
  27050. (function (BABYLON) {
  27051. /**
  27052. * This is a holder class for the physics joint created by the physics plugin.
  27053. * It holds a set of functions to control the underlying joint.
  27054. */
  27055. var PhysicsJoint = (function () {
  27056. function PhysicsJoint(type, jointData) {
  27057. this.type = type;
  27058. this.jointData = jointData;
  27059. jointData.nativeParams = jointData.nativeParams || {};
  27060. }
  27061. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  27062. get: function () {
  27063. return this._physicsJoint;
  27064. },
  27065. set: function (newJoint) {
  27066. if (this._physicsJoint) {
  27067. }
  27068. this._physicsJoint = newJoint;
  27069. },
  27070. enumerable: true,
  27071. configurable: true
  27072. });
  27073. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  27074. set: function (physicsPlugin) {
  27075. this._physicsPlugin = physicsPlugin;
  27076. },
  27077. enumerable: true,
  27078. configurable: true
  27079. });
  27080. /**
  27081. * Execute a function that is physics-plugin specific.
  27082. * @param {Function} func the function that will be executed.
  27083. * It accepts two parameters: the physics world and the physics joint.
  27084. */
  27085. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  27086. func(this._physicsPlugin.world, this._physicsJoint);
  27087. };
  27088. //TODO check if the native joints are the same
  27089. //Joint Types
  27090. PhysicsJoint.DistanceJoint = 0;
  27091. PhysicsJoint.HingeJoint = 1;
  27092. PhysicsJoint.BallAndSocketJoint = 2;
  27093. PhysicsJoint.WheelJoint = 3;
  27094. PhysicsJoint.SliderJoint = 4;
  27095. //OIMO
  27096. PhysicsJoint.PrismaticJoint = 5;
  27097. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  27098. PhysicsJoint.UniversalJoint = 6;
  27099. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  27100. //Cannon
  27101. //Similar to a Ball-Joint. Different in params
  27102. PhysicsJoint.PointToPointJoint = 8;
  27103. //Cannon only at the moment
  27104. PhysicsJoint.SpringJoint = 9;
  27105. return PhysicsJoint;
  27106. })();
  27107. BABYLON.PhysicsJoint = PhysicsJoint;
  27108. /**
  27109. * A class representing a physics distance joint.
  27110. */
  27111. var DistanceJoint = (function (_super) {
  27112. __extends(DistanceJoint, _super);
  27113. function DistanceJoint(jointData) {
  27114. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  27115. }
  27116. /**
  27117. * Update the predefined distance.
  27118. */
  27119. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  27120. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  27121. };
  27122. return DistanceJoint;
  27123. })(PhysicsJoint);
  27124. BABYLON.DistanceJoint = DistanceJoint;
  27125. var MotorEnabledJoint = (function (_super) {
  27126. __extends(MotorEnabledJoint, _super);
  27127. function MotorEnabledJoint(type, jointData) {
  27128. _super.call(this, type, jointData);
  27129. }
  27130. /**
  27131. * Set the motor values.
  27132. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27133. * @param {number} force the force to apply
  27134. * @param {number} maxForce max force for this motor.
  27135. */
  27136. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  27137. this._physicsPlugin.setMotor(this, force, maxForce);
  27138. };
  27139. /**
  27140. * Set the motor's limits.
  27141. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27142. */
  27143. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27144. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27145. };
  27146. return MotorEnabledJoint;
  27147. })(PhysicsJoint);
  27148. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  27149. /**
  27150. * This class represents a single hinge physics joint
  27151. */
  27152. var HingeJoint = (function (_super) {
  27153. __extends(HingeJoint, _super);
  27154. function HingeJoint(jointData) {
  27155. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  27156. }
  27157. /**
  27158. * Set the motor values.
  27159. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27160. * @param {number} force the force to apply
  27161. * @param {number} maxForce max force for this motor.
  27162. */
  27163. HingeJoint.prototype.setMotor = function (force, maxForce) {
  27164. this._physicsPlugin.setMotor(this, force, maxForce);
  27165. };
  27166. /**
  27167. * Set the motor's limits.
  27168. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27169. */
  27170. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  27171. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  27172. };
  27173. return HingeJoint;
  27174. })(MotorEnabledJoint);
  27175. BABYLON.HingeJoint = HingeJoint;
  27176. /**
  27177. * This class represents a dual hinge physics joint (same as wheel joint)
  27178. */
  27179. var Hinge2Joint = (function (_super) {
  27180. __extends(Hinge2Joint, _super);
  27181. function Hinge2Joint(jointData) {
  27182. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  27183. }
  27184. /**
  27185. * Set the motor values.
  27186. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27187. * @param {number} force the force to apply
  27188. * @param {number} maxForce max force for this motor.
  27189. * @param {motorIndex} the motor's index, 0 or 1.
  27190. */
  27191. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  27192. if (motorIndex === void 0) { motorIndex = 0; }
  27193. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  27194. };
  27195. /**
  27196. * Set the motor limits.
  27197. * Attention, this function is plugin specific. Engines won't react 100% the same.
  27198. * @param {number} upperLimit the upper limit
  27199. * @param {number} lowerLimit lower limit
  27200. * @param {motorIndex} the motor's index, 0 or 1.
  27201. */
  27202. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  27203. if (motorIndex === void 0) { motorIndex = 0; }
  27204. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  27205. };
  27206. return Hinge2Joint;
  27207. })(MotorEnabledJoint);
  27208. BABYLON.Hinge2Joint = Hinge2Joint;
  27209. })(BABYLON || (BABYLON = {}));
  27210. var BABYLON;
  27211. (function (BABYLON) {
  27212. var PhysicsImpostor = (function () {
  27213. function PhysicsImpostor(object, type, _options, _scene) {
  27214. var _this = this;
  27215. if (_options === void 0) { _options = { mass: 0 }; }
  27216. this.object = object;
  27217. this.type = type;
  27218. this._options = _options;
  27219. this._scene = _scene;
  27220. this._bodyUpdateRequired = false;
  27221. this._onBeforePhysicsStepCallbacks = new Array();
  27222. this._onAfterPhysicsStepCallbacks = new Array();
  27223. this._onPhysicsCollideCallbacks = [];
  27224. this._deltaPosition = BABYLON.Vector3.Zero();
  27225. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  27226. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  27227. /**
  27228. * this function is executed by the physics engine.
  27229. */
  27230. this.beforeStep = function () {
  27231. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  27232. //conjugate deltaRotation
  27233. if (_this._deltaRotationConjugated) {
  27234. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  27235. }
  27236. else {
  27237. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  27238. }
  27239. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  27240. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  27241. func(_this);
  27242. });
  27243. };
  27244. /**
  27245. * this function is executed by the physics engine.
  27246. */
  27247. this.afterStep = function () {
  27248. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  27249. func(_this);
  27250. });
  27251. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  27252. _this.object.position.addInPlace(_this._deltaPosition);
  27253. if (_this._deltaRotation) {
  27254. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  27255. }
  27256. };
  27257. //event and body object due to cannon's event-based architecture.
  27258. this.onCollide = function (e) {
  27259. if (!_this._onPhysicsCollideCallbacks.length)
  27260. return;
  27261. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  27262. if (otherImpostor) {
  27263. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  27264. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  27265. }).forEach(function (obj) {
  27266. obj.callback(_this, otherImpostor);
  27267. });
  27268. }
  27269. };
  27270. //sanity check!
  27271. if (!this.object) {
  27272. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  27273. return;
  27274. }
  27275. //legacy support for old syntax.
  27276. if (!this._scene && object.getScene) {
  27277. this._scene = object.getScene();
  27278. }
  27279. this._physicsEngine = this._scene.getPhysicsEngine();
  27280. if (!this._physicsEngine) {
  27281. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  27282. }
  27283. else {
  27284. //set the object's quaternion, if not set
  27285. if (!this.object.rotationQuaternion) {
  27286. if (this.object.rotation) {
  27287. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  27288. }
  27289. else {
  27290. this.object.rotationQuaternion = new BABYLON.Quaternion();
  27291. }
  27292. }
  27293. //default options params
  27294. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  27295. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  27296. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  27297. this._joints = [];
  27298. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27299. if (!this.object.parent) {
  27300. this._init();
  27301. }
  27302. }
  27303. }
  27304. /**
  27305. * This function will completly initialize this impostor.
  27306. * It will create a new body - but only if this mesh has no parent.
  27307. * If it has, this impostor will not be used other than to define the impostor
  27308. * of the child mesh.
  27309. */
  27310. PhysicsImpostor.prototype._init = function () {
  27311. this._physicsEngine.removeImpostor(this);
  27312. this.physicsBody = null;
  27313. this._parent = this._parent || this._getPhysicsParent();
  27314. if (!this.parent) {
  27315. this._physicsEngine.addImpostor(this);
  27316. }
  27317. };
  27318. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27319. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27320. var parentMesh = this.object.parent;
  27321. return parentMesh.physicsImpostor;
  27322. }
  27323. return;
  27324. };
  27325. /**
  27326. * Should a new body be generated.
  27327. */
  27328. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27329. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27330. };
  27331. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27332. this.forceUpdate();
  27333. };
  27334. /**
  27335. * Force a regeneration of this or the parent's impostor's body.
  27336. * Use under cautious - This will remove all joints already implemented.
  27337. */
  27338. PhysicsImpostor.prototype.forceUpdate = function () {
  27339. this._init();
  27340. if (this.parent) {
  27341. this.parent.forceUpdate();
  27342. }
  27343. };
  27344. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27345. /*public get mesh(): AbstractMesh {
  27346. return this._mesh;
  27347. }*/
  27348. /**
  27349. * Gets the body that holds this impostor. Either its own, or its parent.
  27350. */
  27351. get: function () {
  27352. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27353. },
  27354. /**
  27355. * Set the physics body. Used mainly by the physics engine/plugin
  27356. */
  27357. set: function (physicsBody) {
  27358. if (this._physicsBody) {
  27359. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27360. }
  27361. this._physicsBody = physicsBody;
  27362. this.resetUpdateFlags();
  27363. },
  27364. enumerable: true,
  27365. configurable: true
  27366. });
  27367. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  27368. get: function () {
  27369. return this._parent;
  27370. },
  27371. enumerable: true,
  27372. configurable: true
  27373. });
  27374. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  27375. this._bodyUpdateRequired = false;
  27376. };
  27377. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27378. if (this.object.getBoundingInfo) {
  27379. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27380. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27381. }
  27382. else {
  27383. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27384. }
  27385. };
  27386. PhysicsImpostor.prototype.getObjectCenter = function () {
  27387. if (this.object.getBoundingInfo) {
  27388. return this.object.getBoundingInfo().boundingBox.center;
  27389. }
  27390. else {
  27391. return this.object.position;
  27392. }
  27393. };
  27394. /**
  27395. * Get a specific parametes from the options parameter.
  27396. */
  27397. PhysicsImpostor.prototype.getParam = function (paramName) {
  27398. return this._options[paramName];
  27399. };
  27400. /**
  27401. * Sets a specific parameter in the options given to the physics plugin
  27402. */
  27403. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27404. this._options[paramName] = value;
  27405. this._bodyUpdateRequired = true;
  27406. };
  27407. /**
  27408. * Specifically change the body's mass option. Won't recreate the physics body object
  27409. */
  27410. PhysicsImpostor.prototype.setMass = function (mass) {
  27411. if (this.getParam("mass") !== mass) {
  27412. this.setParam("mass", mass);
  27413. }
  27414. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27415. };
  27416. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27417. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27418. };
  27419. /**
  27420. * Set the body's linear velocity.
  27421. */
  27422. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27423. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27424. };
  27425. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27426. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27427. };
  27428. /**
  27429. * Set the body's linear velocity.
  27430. */
  27431. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27432. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27433. };
  27434. /**
  27435. * Execute a function with the physics plugin native code.
  27436. * Provide a function the will have two variables - the world object and the physics body object.
  27437. */
  27438. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27439. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27440. };
  27441. /**
  27442. * Register a function that will be executed before the physics world is stepping forward.
  27443. */
  27444. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27445. this._onBeforePhysicsStepCallbacks.push(func);
  27446. };
  27447. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27448. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27449. if (index > -1) {
  27450. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27451. }
  27452. else {
  27453. BABYLON.Tools.Warn("Function to remove was not found");
  27454. }
  27455. };
  27456. /**
  27457. * Register a function that will be executed after the physics step
  27458. */
  27459. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27460. this._onAfterPhysicsStepCallbacks.push(func);
  27461. };
  27462. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27463. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27464. if (index > -1) {
  27465. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27466. }
  27467. else {
  27468. BABYLON.Tools.Warn("Function to remove was not found");
  27469. }
  27470. };
  27471. /**
  27472. * register a function that will be executed when this impostor collides against a different body.
  27473. */
  27474. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27475. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27476. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27477. };
  27478. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27479. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27480. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27481. if (index > -1) {
  27482. this._onPhysicsCollideCallbacks.splice(index, 1);
  27483. }
  27484. else {
  27485. BABYLON.Tools.Warn("Function to remove was not found");
  27486. }
  27487. };
  27488. /**
  27489. * Apply a force
  27490. */
  27491. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27492. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27493. };
  27494. /**
  27495. * Apply an impulse
  27496. */
  27497. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27498. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27499. };
  27500. /**
  27501. * A help function to create a joint.
  27502. */
  27503. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27504. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27505. this.addJoint(otherImpostor, joint);
  27506. };
  27507. /**
  27508. * Add a joint to this impostor with a different impostor.
  27509. */
  27510. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27511. this._joints.push({
  27512. otherImpostor: otherImpostor,
  27513. joint: joint
  27514. });
  27515. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27516. };
  27517. /**
  27518. * Will keep this body still, in a sleep mode.
  27519. */
  27520. PhysicsImpostor.prototype.sleep = function () {
  27521. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27522. };
  27523. /**
  27524. * Wake the body up.
  27525. */
  27526. PhysicsImpostor.prototype.wakeUp = function () {
  27527. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27528. };
  27529. PhysicsImpostor.prototype.clone = function (newObject) {
  27530. if (!newObject)
  27531. return null;
  27532. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27533. };
  27534. PhysicsImpostor.prototype.dispose = function () {
  27535. var _this = this;
  27536. //no dispose if no physics engine is available.
  27537. if (!this._physicsEngine) {
  27538. return;
  27539. }
  27540. this._joints.forEach(function (j) {
  27541. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  27542. });
  27543. //dispose the physics body
  27544. this._physicsEngine.removeImpostor(this);
  27545. if (this.parent) {
  27546. this.parent.forceUpdate();
  27547. }
  27548. else {
  27549. }
  27550. };
  27551. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27552. this._deltaPosition.copyFrom(position);
  27553. };
  27554. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27555. if (!this._deltaRotation) {
  27556. this._deltaRotation = new BABYLON.Quaternion();
  27557. }
  27558. this._deltaRotation.copyFrom(rotation);
  27559. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27560. };
  27561. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27562. //Impostor types
  27563. PhysicsImpostor.NoImpostor = 0;
  27564. PhysicsImpostor.SphereImpostor = 1;
  27565. PhysicsImpostor.BoxImpostor = 2;
  27566. PhysicsImpostor.PlaneImpostor = 3;
  27567. PhysicsImpostor.MeshImpostor = 4;
  27568. PhysicsImpostor.CylinderImpostor = 7;
  27569. PhysicsImpostor.ParticleImpostor = 8;
  27570. PhysicsImpostor.HeightmapImpostor = 9;
  27571. return PhysicsImpostor;
  27572. })();
  27573. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27574. })(BABYLON || (BABYLON = {}));
  27575. var BABYLON;
  27576. (function (BABYLON) {
  27577. var PhysicsEngine = (function () {
  27578. function PhysicsEngine(gravity, _physicsPlugin) {
  27579. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27580. this._physicsPlugin = _physicsPlugin;
  27581. //new methods and parameters
  27582. this._impostors = [];
  27583. this._joints = [];
  27584. if (!this._physicsPlugin.isSupported()) {
  27585. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27586. + "Please make sure it is included.");
  27587. }
  27588. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27589. this.setGravity(gravity);
  27590. this.setTimeStep();
  27591. }
  27592. PhysicsEngine.prototype.setGravity = function (gravity) {
  27593. this.gravity = gravity;
  27594. this._physicsPlugin.setGravity(this.gravity);
  27595. };
  27596. /**
  27597. * Set the time step of the physics engine.
  27598. * default is 1/60.
  27599. * To slow it down, enter 1/600 for example.
  27600. * To speed it up, 1/30
  27601. * @param {number} newTimeStep the new timestep to apply to this world.
  27602. */
  27603. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27604. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27605. this._physicsPlugin.setTimeStep(newTimeStep);
  27606. };
  27607. PhysicsEngine.prototype.dispose = function () {
  27608. this._impostors.forEach(function (impostor) {
  27609. impostor.dispose();
  27610. });
  27611. this._physicsPlugin.dispose();
  27612. };
  27613. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27614. return this._physicsPlugin.name;
  27615. };
  27616. /**
  27617. * Adding a new impostor for the impostor tracking.
  27618. * This will be done by the impostor itself.
  27619. * @param {PhysicsImpostor} impostor the impostor to add
  27620. */
  27621. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27622. impostor.uniqueId = this._impostors.push(impostor);
  27623. //if no parent, generate the body
  27624. if (!impostor.parent) {
  27625. this._physicsPlugin.generatePhysicsBody(impostor);
  27626. }
  27627. };
  27628. /**
  27629. * Remove an impostor from the engine.
  27630. * This impostor and its mesh will not longer be updated by the physics engine.
  27631. * @param {PhysicsImpostor} impostor the impostor to remove
  27632. */
  27633. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27634. var index = this._impostors.indexOf(impostor);
  27635. if (index > -1) {
  27636. var removed = this._impostors.splice(index, 1);
  27637. //Is it needed?
  27638. if (removed.length) {
  27639. //this will also remove it from the world.
  27640. removed[0].physicsBody = null;
  27641. }
  27642. }
  27643. };
  27644. /**
  27645. * Add a joint to the physics engine
  27646. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27647. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27648. * @param {PhysicsJoint} the joint that will connect both impostors.
  27649. */
  27650. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27651. var impostorJoint = {
  27652. mainImpostor: mainImpostor,
  27653. connectedImpostor: connectedImpostor,
  27654. joint: joint
  27655. };
  27656. joint.physicsPlugin = this._physicsPlugin;
  27657. this._joints.push(impostorJoint);
  27658. this._physicsPlugin.generateJoint(impostorJoint);
  27659. };
  27660. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27661. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27662. return (impostorJoint.connectedImpostor === connectedImpostor
  27663. && impostorJoint.joint === joint
  27664. && impostorJoint.mainImpostor === mainImpostor);
  27665. });
  27666. if (matchingJoints.length) {
  27667. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27668. }
  27669. };
  27670. /**
  27671. * Called by the scene. no need to call it.
  27672. */
  27673. PhysicsEngine.prototype._step = function (delta) {
  27674. var _this = this;
  27675. //check if any mesh has no body / requires an update
  27676. this._impostors.forEach(function (impostor) {
  27677. if (impostor.isBodyInitRequired()) {
  27678. _this._physicsPlugin.generatePhysicsBody(impostor);
  27679. }
  27680. });
  27681. if (delta > 0.1) {
  27682. delta = 0.1;
  27683. }
  27684. else if (delta <= 0) {
  27685. delta = 1.0 / 60.0;
  27686. }
  27687. this._physicsPlugin.executeStep(delta, this._impostors);
  27688. };
  27689. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27690. return this._physicsPlugin;
  27691. };
  27692. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27693. for (var i = 0; i < this._impostors.length; ++i) {
  27694. if (this._impostors[i].object === object) {
  27695. return this._impostors[i];
  27696. }
  27697. }
  27698. };
  27699. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27700. for (var i = 0; i < this._impostors.length; ++i) {
  27701. if (this._impostors[i].physicsBody === body) {
  27702. return this._impostors[i];
  27703. }
  27704. }
  27705. };
  27706. // Statics, Legacy support.
  27707. /**
  27708. * @Deprecated
  27709. *
  27710. */
  27711. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27712. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27713. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27714. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27715. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27716. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27717. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27718. PhysicsEngine.CapsuleImpostor = -1;
  27719. PhysicsEngine.ConeImpostor = -1;
  27720. PhysicsEngine.ConvexHullImpostor = -1;
  27721. PhysicsEngine.Epsilon = 0.001;
  27722. return PhysicsEngine;
  27723. })();
  27724. BABYLON.PhysicsEngine = PhysicsEngine;
  27725. })(BABYLON || (BABYLON = {}));
  27726. var BABYLON;
  27727. (function (BABYLON) {
  27728. var VertexData = (function () {
  27729. function VertexData() {
  27730. }
  27731. VertexData.prototype.set = function (data, kind) {
  27732. switch (kind) {
  27733. case BABYLON.VertexBuffer.PositionKind:
  27734. this.positions = data;
  27735. break;
  27736. case BABYLON.VertexBuffer.NormalKind:
  27737. this.normals = data;
  27738. break;
  27739. case BABYLON.VertexBuffer.UVKind:
  27740. this.uvs = data;
  27741. break;
  27742. case BABYLON.VertexBuffer.UV2Kind:
  27743. this.uvs2 = data;
  27744. break;
  27745. case BABYLON.VertexBuffer.UV3Kind:
  27746. this.uvs3 = data;
  27747. break;
  27748. case BABYLON.VertexBuffer.UV4Kind:
  27749. this.uvs4 = data;
  27750. break;
  27751. case BABYLON.VertexBuffer.UV5Kind:
  27752. this.uvs5 = data;
  27753. break;
  27754. case BABYLON.VertexBuffer.UV6Kind:
  27755. this.uvs6 = data;
  27756. break;
  27757. case BABYLON.VertexBuffer.ColorKind:
  27758. this.colors = data;
  27759. break;
  27760. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27761. this.matricesIndices = data;
  27762. break;
  27763. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27764. this.matricesWeights = data;
  27765. break;
  27766. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27767. this.matricesIndicesExtra = data;
  27768. break;
  27769. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27770. this.matricesWeightsExtra = data;
  27771. break;
  27772. }
  27773. };
  27774. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27775. this._applyTo(mesh, updatable);
  27776. };
  27777. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27778. this._applyTo(geometry, updatable);
  27779. };
  27780. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27781. this._update(mesh);
  27782. };
  27783. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27784. this._update(geometry);
  27785. };
  27786. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27787. if (this.positions) {
  27788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27789. }
  27790. if (this.normals) {
  27791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27792. }
  27793. if (this.uvs) {
  27794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27795. }
  27796. if (this.uvs2) {
  27797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27798. }
  27799. if (this.uvs3) {
  27800. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27801. }
  27802. if (this.uvs4) {
  27803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27804. }
  27805. if (this.uvs5) {
  27806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27807. }
  27808. if (this.uvs6) {
  27809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27810. }
  27811. if (this.colors) {
  27812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27813. }
  27814. if (this.matricesIndices) {
  27815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27816. }
  27817. if (this.matricesWeights) {
  27818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27819. }
  27820. if (this.matricesIndicesExtra) {
  27821. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27822. }
  27823. if (this.matricesWeightsExtra) {
  27824. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27825. }
  27826. if (this.indices) {
  27827. meshOrGeometry.setIndices(this.indices);
  27828. }
  27829. };
  27830. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27831. if (this.positions) {
  27832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27833. }
  27834. if (this.normals) {
  27835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27836. }
  27837. if (this.uvs) {
  27838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27839. }
  27840. if (this.uvs2) {
  27841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27842. }
  27843. if (this.uvs3) {
  27844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27845. }
  27846. if (this.uvs4) {
  27847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27848. }
  27849. if (this.uvs5) {
  27850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27851. }
  27852. if (this.uvs6) {
  27853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27854. }
  27855. if (this.colors) {
  27856. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27857. }
  27858. if (this.matricesIndices) {
  27859. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27860. }
  27861. if (this.matricesWeights) {
  27862. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27863. }
  27864. if (this.matricesIndicesExtra) {
  27865. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27866. }
  27867. if (this.matricesWeightsExtra) {
  27868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27869. }
  27870. if (this.indices) {
  27871. meshOrGeometry.setIndices(this.indices);
  27872. }
  27873. };
  27874. VertexData.prototype.transform = function (matrix) {
  27875. var transformed = BABYLON.Vector3.Zero();
  27876. var index;
  27877. if (this.positions) {
  27878. var position = BABYLON.Vector3.Zero();
  27879. for (index = 0; index < this.positions.length; index += 3) {
  27880. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27881. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27882. this.positions[index] = transformed.x;
  27883. this.positions[index + 1] = transformed.y;
  27884. this.positions[index + 2] = transformed.z;
  27885. }
  27886. }
  27887. if (this.normals) {
  27888. var normal = BABYLON.Vector3.Zero();
  27889. for (index = 0; index < this.normals.length; index += 3) {
  27890. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27891. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27892. this.normals[index] = transformed.x;
  27893. this.normals[index + 1] = transformed.y;
  27894. this.normals[index + 2] = transformed.z;
  27895. }
  27896. }
  27897. };
  27898. VertexData.prototype.merge = function (other) {
  27899. if (other.indices) {
  27900. if (!this.indices) {
  27901. this.indices = [];
  27902. }
  27903. var offset = this.positions ? this.positions.length / 3 : 0;
  27904. for (var index = 0; index < other.indices.length; index++) {
  27905. //TODO check type - if Int32Array!
  27906. this.indices.push(other.indices[index] + offset);
  27907. }
  27908. }
  27909. this.positions = this._mergeElement(this.positions, other.positions);
  27910. this.normals = this._mergeElement(this.normals, other.normals);
  27911. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27912. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27913. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27914. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27915. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27916. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27917. this.colors = this._mergeElement(this.colors, other.colors);
  27918. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27919. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27920. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27921. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27922. };
  27923. VertexData.prototype._mergeElement = function (source, other) {
  27924. if (!other)
  27925. return source;
  27926. if (!source)
  27927. return other;
  27928. var len = other.length + source.length;
  27929. var isSrcTypedArray = source instanceof Float32Array;
  27930. var isOthTypedArray = other instanceof Float32Array;
  27931. // use non-loop method when the source is Float32Array
  27932. if (isSrcTypedArray) {
  27933. var ret32 = new Float32Array(len);
  27934. ret32.set(source);
  27935. ret32.set(other, source.length);
  27936. return ret32;
  27937. }
  27938. else if (!isOthTypedArray) {
  27939. return source.concat(other);
  27940. }
  27941. else {
  27942. var ret = source.slice(0); // copy source to a separate array
  27943. for (var i = 0, len = other.length; i < len; i++) {
  27944. ret.push(other[i]);
  27945. }
  27946. return ret;
  27947. }
  27948. };
  27949. VertexData.prototype.serialize = function () {
  27950. var serializationObject = this.serialize();
  27951. if (this.positions) {
  27952. serializationObject.positions = this.positions;
  27953. }
  27954. if (this.normals) {
  27955. serializationObject.normals = this.normals;
  27956. }
  27957. if (this.uvs) {
  27958. serializationObject.uvs = this.uvs;
  27959. }
  27960. if (this.uvs2) {
  27961. serializationObject.uvs2 = this.uvs2;
  27962. }
  27963. if (this.uvs3) {
  27964. serializationObject.uvs3 = this.uvs3;
  27965. }
  27966. if (this.uvs4) {
  27967. serializationObject.uvs4 = this.uvs4;
  27968. }
  27969. if (this.uvs5) {
  27970. serializationObject.uvs5 = this.uvs5;
  27971. }
  27972. if (this.uvs6) {
  27973. serializationObject.uvs6 = this.uvs6;
  27974. }
  27975. if (this.colors) {
  27976. serializationObject.colors = this.colors;
  27977. }
  27978. if (this.matricesIndices) {
  27979. serializationObject.matricesIndices = this.matricesIndices;
  27980. serializationObject.matricesIndices._isExpanded = true;
  27981. }
  27982. if (this.matricesWeights) {
  27983. serializationObject.matricesWeights = this.matricesWeights;
  27984. }
  27985. if (this.matricesIndicesExtra) {
  27986. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27987. serializationObject.matricesIndicesExtra._isExpanded = true;
  27988. }
  27989. if (this.matricesWeightsExtra) {
  27990. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27991. }
  27992. serializationObject.indices = this.indices;
  27993. return serializationObject;
  27994. };
  27995. // Statics
  27996. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27997. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27998. };
  27999. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  28000. return VertexData._ExtractFrom(geometry, copyWhenShared);
  28001. };
  28002. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  28003. var result = new VertexData();
  28004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28005. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  28006. }
  28007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28008. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  28009. }
  28010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28011. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  28012. }
  28013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28014. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  28015. }
  28016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28017. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  28018. }
  28019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28020. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  28021. }
  28022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28023. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  28024. }
  28025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28026. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  28027. }
  28028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28029. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  28030. }
  28031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28032. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  28033. }
  28034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28035. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  28036. }
  28037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28038. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  28039. }
  28040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28041. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  28042. }
  28043. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28044. return result;
  28045. };
  28046. VertexData.CreateRibbon = function (options) {
  28047. var pathArray = options.pathArray;
  28048. var closeArray = options.closeArray || false;
  28049. var closePath = options.closePath || false;
  28050. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28051. var offset = options.offset || defaultOffset;
  28052. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28053. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28054. var positions = [];
  28055. var indices = [];
  28056. var normals = [];
  28057. var uvs = [];
  28058. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28059. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28060. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28061. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28062. var minlg; // minimal length among all paths from pathArray
  28063. var lg = []; // array of path lengths : nb of vertex per path
  28064. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28065. var p; // path iterator
  28066. var i; // point iterator
  28067. var j; // point iterator
  28068. // if single path in pathArray
  28069. if (pathArray.length < 2) {
  28070. var ar1 = [];
  28071. var ar2 = [];
  28072. for (i = 0; i < pathArray[0].length - offset; i++) {
  28073. ar1.push(pathArray[0][i]);
  28074. ar2.push(pathArray[0][i + offset]);
  28075. }
  28076. pathArray = [ar1, ar2];
  28077. }
  28078. // positions and horizontal distances (u)
  28079. var idc = 0;
  28080. var closePathCorr = (closePath) ? 1 : 0;
  28081. var path;
  28082. var l;
  28083. minlg = pathArray[0].length;
  28084. var vectlg;
  28085. var dist;
  28086. for (p = 0; p < pathArray.length; p++) {
  28087. uTotalDistance[p] = 0;
  28088. us[p] = [0];
  28089. path = pathArray[p];
  28090. l = path.length;
  28091. minlg = (minlg < l) ? minlg : l;
  28092. j = 0;
  28093. while (j < l) {
  28094. positions.push(path[j].x, path[j].y, path[j].z);
  28095. if (j > 0) {
  28096. vectlg = path[j].subtract(path[j - 1]).length();
  28097. dist = vectlg + uTotalDistance[p];
  28098. us[p].push(dist);
  28099. uTotalDistance[p] = dist;
  28100. }
  28101. j++;
  28102. }
  28103. if (closePath) {
  28104. j--;
  28105. positions.push(path[0].x, path[0].y, path[0].z);
  28106. vectlg = path[j].subtract(path[0]).length();
  28107. dist = vectlg + uTotalDistance[p];
  28108. us[p].push(dist);
  28109. uTotalDistance[p] = dist;
  28110. }
  28111. lg[p] = l + closePathCorr;
  28112. idx[p] = idc;
  28113. idc += (l + closePathCorr);
  28114. }
  28115. // vertical distances (v)
  28116. var path1;
  28117. var path2;
  28118. var vertex1;
  28119. var vertex2;
  28120. for (i = 0; i < minlg + closePathCorr; i++) {
  28121. vTotalDistance[i] = 0;
  28122. vs[i] = [0];
  28123. for (p = 0; p < pathArray.length - 1; p++) {
  28124. path1 = pathArray[p];
  28125. path2 = pathArray[p + 1];
  28126. if (i === minlg) {
  28127. vertex1 = path1[0];
  28128. vertex2 = path2[0];
  28129. }
  28130. else {
  28131. vertex1 = path1[i];
  28132. vertex2 = path2[i];
  28133. }
  28134. vectlg = vertex2.subtract(vertex1).length();
  28135. dist = vectlg + vTotalDistance[i];
  28136. vs[i].push(dist);
  28137. vTotalDistance[i] = dist;
  28138. }
  28139. if (closeArray) {
  28140. path1 = pathArray[p];
  28141. path2 = pathArray[0];
  28142. if (i === minlg) {
  28143. vertex2 = path2[0];
  28144. }
  28145. vectlg = vertex2.subtract(vertex1).length();
  28146. dist = vectlg + vTotalDistance[i];
  28147. vTotalDistance[i] = dist;
  28148. }
  28149. }
  28150. // uvs
  28151. var u;
  28152. var v;
  28153. for (p = 0; p < pathArray.length; p++) {
  28154. for (i = 0; i < minlg + closePathCorr; i++) {
  28155. u = us[p][i] / uTotalDistance[p];
  28156. v = vs[i][p] / vTotalDistance[i];
  28157. uvs.push(u, v);
  28158. }
  28159. }
  28160. // indices
  28161. p = 0; // path index
  28162. var pi = 0; // positions array index
  28163. var l1 = lg[p] - 1; // path1 length
  28164. var l2 = lg[p + 1] - 1; // path2 length
  28165. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28166. var shft = idx[1] - idx[0]; // shift
  28167. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28168. while (pi <= min && p < path1nb) {
  28169. // 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
  28170. indices.push(pi, pi + shft, pi + 1);
  28171. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28172. pi += 1;
  28173. if (pi === min) {
  28174. p++;
  28175. if (p === lg.length - 1) {
  28176. shft = idx[0] - idx[p];
  28177. l1 = lg[p] - 1;
  28178. l2 = lg[0] - 1;
  28179. }
  28180. else {
  28181. shft = idx[p + 1] - idx[p];
  28182. l1 = lg[p] - 1;
  28183. l2 = lg[p + 1] - 1;
  28184. }
  28185. pi = idx[p];
  28186. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28187. }
  28188. }
  28189. // normals
  28190. VertexData.ComputeNormals(positions, indices, normals);
  28191. if (closePath) {
  28192. var indexFirst = 0;
  28193. var indexLast = 0;
  28194. for (p = 0; p < pathArray.length; p++) {
  28195. indexFirst = idx[p] * 3;
  28196. if (p + 1 < pathArray.length) {
  28197. indexLast = (idx[p + 1] - 1) * 3;
  28198. }
  28199. else {
  28200. indexLast = normals.length - 3;
  28201. }
  28202. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28203. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28204. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28205. normals[indexLast] = normals[indexFirst];
  28206. normals[indexLast + 1] = normals[indexFirst + 1];
  28207. normals[indexLast + 2] = normals[indexFirst + 2];
  28208. }
  28209. }
  28210. // sides
  28211. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28212. // Result
  28213. var vertexData = new VertexData();
  28214. vertexData.indices = indices;
  28215. vertexData.positions = positions;
  28216. vertexData.normals = normals;
  28217. vertexData.uvs = uvs;
  28218. if (closePath) {
  28219. vertexData._idx = idx;
  28220. }
  28221. return vertexData;
  28222. };
  28223. VertexData.CreateBox = function (options) {
  28224. var normalsSource = [
  28225. new BABYLON.Vector3(0, 0, 1),
  28226. new BABYLON.Vector3(0, 0, -1),
  28227. new BABYLON.Vector3(1, 0, 0),
  28228. new BABYLON.Vector3(-1, 0, 0),
  28229. new BABYLON.Vector3(0, 1, 0),
  28230. new BABYLON.Vector3(0, -1, 0)
  28231. ];
  28232. var indices = [];
  28233. var positions = [];
  28234. var normals = [];
  28235. var uvs = [];
  28236. var width = options.width || options.size || 1;
  28237. var height = options.height || options.size || 1;
  28238. var depth = options.depth || options.size || 1;
  28239. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28240. var faceUV = options.faceUV || new Array(6);
  28241. var faceColors = options.faceColors;
  28242. var colors = [];
  28243. // default face colors and UV if undefined
  28244. for (var f = 0; f < 6; f++) {
  28245. if (faceUV[f] === undefined) {
  28246. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28247. }
  28248. if (faceColors && faceColors[f] === undefined) {
  28249. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28250. }
  28251. }
  28252. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28253. // Create each face in turn.
  28254. for (var index = 0; index < normalsSource.length; index++) {
  28255. var normal = normalsSource[index];
  28256. // Get two vectors perpendicular to the face normal and to each other.
  28257. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28258. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28259. // Six indices (two triangles) per face.
  28260. var verticesLength = positions.length / 3;
  28261. indices.push(verticesLength);
  28262. indices.push(verticesLength + 1);
  28263. indices.push(verticesLength + 2);
  28264. indices.push(verticesLength);
  28265. indices.push(verticesLength + 2);
  28266. indices.push(verticesLength + 3);
  28267. // Four vertices per face.
  28268. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28269. positions.push(vertex.x, vertex.y, vertex.z);
  28270. normals.push(normal.x, normal.y, normal.z);
  28271. uvs.push(faceUV[index].z, faceUV[index].w);
  28272. if (faceColors) {
  28273. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28274. }
  28275. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28276. positions.push(vertex.x, vertex.y, vertex.z);
  28277. normals.push(normal.x, normal.y, normal.z);
  28278. uvs.push(faceUV[index].x, faceUV[index].w);
  28279. if (faceColors) {
  28280. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28281. }
  28282. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28283. positions.push(vertex.x, vertex.y, vertex.z);
  28284. normals.push(normal.x, normal.y, normal.z);
  28285. uvs.push(faceUV[index].x, faceUV[index].y);
  28286. if (faceColors) {
  28287. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28288. }
  28289. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28290. positions.push(vertex.x, vertex.y, vertex.z);
  28291. normals.push(normal.x, normal.y, normal.z);
  28292. uvs.push(faceUV[index].z, faceUV[index].y);
  28293. if (faceColors) {
  28294. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28295. }
  28296. }
  28297. // sides
  28298. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28299. // Result
  28300. var vertexData = new VertexData();
  28301. vertexData.indices = indices;
  28302. vertexData.positions = positions;
  28303. vertexData.normals = normals;
  28304. vertexData.uvs = uvs;
  28305. if (faceColors) {
  28306. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28307. vertexData.colors = totalColors;
  28308. }
  28309. return vertexData;
  28310. };
  28311. VertexData.CreateSphere = function (options) {
  28312. var segments = options.segments || 32;
  28313. var diameterX = options.diameterX || options.diameter || 1;
  28314. var diameterY = options.diameterY || options.diameter || 1;
  28315. var diameterZ = options.diameterZ || options.diameter || 1;
  28316. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28317. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28318. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28319. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28320. var totalZRotationSteps = 2 + segments;
  28321. var totalYRotationSteps = 2 * totalZRotationSteps;
  28322. var indices = [];
  28323. var positions = [];
  28324. var normals = [];
  28325. var uvs = [];
  28326. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28327. var normalizedZ = zRotationStep / totalZRotationSteps;
  28328. var angleZ = normalizedZ * Math.PI * slice;
  28329. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28330. var normalizedY = yRotationStep / totalYRotationSteps;
  28331. var angleY = normalizedY * Math.PI * 2 * arc;
  28332. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28333. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28334. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28335. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28336. var vertex = complete.multiply(radius);
  28337. var normal = complete.divide(radius).normalize();
  28338. positions.push(vertex.x, vertex.y, vertex.z);
  28339. normals.push(normal.x, normal.y, normal.z);
  28340. uvs.push(normalizedY, normalizedZ);
  28341. }
  28342. if (zRotationStep > 0) {
  28343. var verticesCount = positions.length / 3;
  28344. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28345. indices.push((firstIndex));
  28346. indices.push((firstIndex + 1));
  28347. indices.push(firstIndex + totalYRotationSteps + 1);
  28348. indices.push((firstIndex + totalYRotationSteps + 1));
  28349. indices.push((firstIndex + 1));
  28350. indices.push((firstIndex + totalYRotationSteps + 2));
  28351. }
  28352. }
  28353. }
  28354. // Sides
  28355. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28356. // Result
  28357. var vertexData = new VertexData();
  28358. vertexData.indices = indices;
  28359. vertexData.positions = positions;
  28360. vertexData.normals = normals;
  28361. vertexData.uvs = uvs;
  28362. return vertexData;
  28363. };
  28364. // Cylinder and cone
  28365. VertexData.CreateCylinder = function (options) {
  28366. var height = options.height || 2;
  28367. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28368. var diameterBottom = options.diameterBottom || options.diameter || 1;
  28369. var tessellation = options.tessellation || 24;
  28370. var subdivisions = options.subdivisions || 1;
  28371. var hasRings = options.hasRings;
  28372. var enclose = options.enclose;
  28373. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28374. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28375. var faceUV = options.faceUV || new Array(3);
  28376. var faceColors = options.faceColors;
  28377. // default face colors and UV if undefined
  28378. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28379. var ringNb = (hasRings) ? subdivisions : 1;
  28380. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28381. var f;
  28382. for (f = 0; f < surfaceNb; f++) {
  28383. if (faceColors && faceColors[f] === undefined) {
  28384. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28385. }
  28386. }
  28387. for (f = 0; f < surfaceNb; f++) {
  28388. if (faceUV && faceUV[f] === undefined) {
  28389. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28390. }
  28391. }
  28392. var indices = [];
  28393. var positions = [];
  28394. var normals = [];
  28395. var uvs = [];
  28396. var colors = [];
  28397. var angle_step = Math.PI * 2 * arc / tessellation;
  28398. var angle;
  28399. var h;
  28400. var radius;
  28401. var tan = (diameterBottom - diameterTop) / 2 / height;
  28402. var ringVertex = BABYLON.Vector3.Zero();
  28403. var ringNormal = BABYLON.Vector3.Zero();
  28404. var ringFirstVertex = BABYLON.Vector3.Zero();
  28405. var ringFirstNormal = BABYLON.Vector3.Zero();
  28406. var quadNormal = BABYLON.Vector3.Zero();
  28407. var Y = BABYLON.Axis.Y;
  28408. // positions, normals, uvs
  28409. var i;
  28410. var j;
  28411. var r;
  28412. var ringIdx = 1;
  28413. var s = 1; // surface index
  28414. var cs = 0;
  28415. var v = 0;
  28416. for (i = 0; i <= subdivisions; i++) {
  28417. h = i / subdivisions;
  28418. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28419. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28420. for (r = 0; r < ringIdx; r++) {
  28421. if (hasRings) {
  28422. s += r;
  28423. }
  28424. if (enclose) {
  28425. s += 2 * r;
  28426. }
  28427. for (j = 0; j <= tessellation; j++) {
  28428. angle = j * angle_step;
  28429. // position
  28430. ringVertex.x = Math.cos(-angle) * radius;
  28431. ringVertex.y = -height / 2 + h * height;
  28432. ringVertex.z = Math.sin(-angle) * radius;
  28433. // normal
  28434. if (diameterTop === 0 && i === subdivisions) {
  28435. // if no top cap, reuse former normals
  28436. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28437. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28438. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28439. }
  28440. else {
  28441. ringNormal.x = ringVertex.x;
  28442. ringNormal.z = ringVertex.z;
  28443. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28444. ringNormal.normalize();
  28445. }
  28446. // keep first ring vertex values for enclose
  28447. if (j === 0) {
  28448. ringFirstVertex.copyFrom(ringVertex);
  28449. ringFirstNormal.copyFrom(ringNormal);
  28450. }
  28451. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28452. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28453. if (hasRings) {
  28454. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28455. }
  28456. else {
  28457. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28458. }
  28459. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28460. if (faceColors) {
  28461. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28462. }
  28463. }
  28464. // if enclose, add four vertices and their dedicated normals
  28465. if (arc !== 1 && enclose) {
  28466. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28467. positions.push(0, ringVertex.y, 0);
  28468. positions.push(0, ringVertex.y, 0);
  28469. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28470. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28471. quadNormal.normalize();
  28472. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28473. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28474. quadNormal.normalize();
  28475. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28476. if (hasRings) {
  28477. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28478. }
  28479. else {
  28480. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28481. }
  28482. uvs.push(faceUV[s + 1].x, v);
  28483. uvs.push(faceUV[s + 1].z, v);
  28484. if (hasRings) {
  28485. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28486. }
  28487. else {
  28488. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28489. }
  28490. uvs.push(faceUV[s + 2].x, v);
  28491. uvs.push(faceUV[s + 2].z, v);
  28492. if (faceColors) {
  28493. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28494. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28495. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28496. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28497. }
  28498. }
  28499. if (cs !== s) {
  28500. cs = s;
  28501. }
  28502. }
  28503. }
  28504. // indices
  28505. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28506. var s;
  28507. i = 0;
  28508. for (s = 0; s < subdivisions; s++) {
  28509. for (j = 0; j < tessellation; j++) {
  28510. var i0 = i * (e + 1) + j;
  28511. var i1 = (i + 1) * (e + 1) + j;
  28512. var i2 = i * (e + 1) + (j + 1);
  28513. var i3 = (i + 1) * (e + 1) + (j + 1);
  28514. indices.push(i0, i1, i2);
  28515. indices.push(i3, i2, i1);
  28516. }
  28517. if (arc !== 1 && enclose) {
  28518. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28519. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28520. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28521. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28522. }
  28523. i = (hasRings) ? (i + 2) : (i + 1);
  28524. }
  28525. // Caps
  28526. var createCylinderCap = function (isTop) {
  28527. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28528. if (radius === 0) {
  28529. return;
  28530. }
  28531. // Cap positions, normals & uvs
  28532. var angle;
  28533. var circleVector;
  28534. var i;
  28535. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28536. var c;
  28537. if (faceColors) {
  28538. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28539. }
  28540. // cap center
  28541. var vbase = positions.length / 3;
  28542. var offset = isTop ? height / 2 : -height / 2;
  28543. var center = new BABYLON.Vector3(0, offset, 0);
  28544. positions.push(center.x, center.y, center.z);
  28545. normals.push(0, isTop ? 1 : -1, 0);
  28546. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28547. if (faceColors) {
  28548. colors.push(c.r, c.g, c.b, c.a);
  28549. }
  28550. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28551. for (i = 0; i <= tessellation; i++) {
  28552. angle = Math.PI * 2 * i * arc / tessellation;
  28553. var cos = Math.cos(-angle);
  28554. var sin = Math.sin(-angle);
  28555. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28556. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28557. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28558. normals.push(0, isTop ? 1 : -1, 0);
  28559. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28560. if (faceColors) {
  28561. colors.push(c.r, c.g, c.b, c.a);
  28562. }
  28563. }
  28564. // Cap indices
  28565. for (i = 0; i < tessellation; i++) {
  28566. if (!isTop) {
  28567. indices.push(vbase);
  28568. indices.push(vbase + (i + 1));
  28569. indices.push(vbase + (i + 2));
  28570. }
  28571. else {
  28572. indices.push(vbase);
  28573. indices.push(vbase + (i + 2));
  28574. indices.push(vbase + (i + 1));
  28575. }
  28576. }
  28577. };
  28578. // add caps to geometry
  28579. createCylinderCap(false);
  28580. createCylinderCap(true);
  28581. // Sides
  28582. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28583. var vertexData = new VertexData();
  28584. vertexData.indices = indices;
  28585. vertexData.positions = positions;
  28586. vertexData.normals = normals;
  28587. vertexData.uvs = uvs;
  28588. if (faceColors) {
  28589. vertexData.colors = colors;
  28590. }
  28591. return vertexData;
  28592. };
  28593. VertexData.CreateTorus = function (options) {
  28594. var indices = [];
  28595. var positions = [];
  28596. var normals = [];
  28597. var uvs = [];
  28598. var diameter = options.diameter || 1;
  28599. var thickness = options.thickness || 0.5;
  28600. var tessellation = options.tessellation || 16;
  28601. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28602. var stride = tessellation + 1;
  28603. for (var i = 0; i <= tessellation; i++) {
  28604. var u = i / tessellation;
  28605. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28606. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28607. for (var j = 0; j <= tessellation; j++) {
  28608. var v = 1 - j / tessellation;
  28609. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28610. var dx = Math.cos(innerAngle);
  28611. var dy = Math.sin(innerAngle);
  28612. // Create a vertex.
  28613. var normal = new BABYLON.Vector3(dx, dy, 0);
  28614. var position = normal.scale(thickness / 2);
  28615. var textureCoordinate = new BABYLON.Vector2(u, v);
  28616. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28617. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28618. positions.push(position.x, position.y, position.z);
  28619. normals.push(normal.x, normal.y, normal.z);
  28620. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28621. // And create indices for two triangles.
  28622. var nextI = (i + 1) % stride;
  28623. var nextJ = (j + 1) % stride;
  28624. indices.push(i * stride + j);
  28625. indices.push(i * stride + nextJ);
  28626. indices.push(nextI * stride + j);
  28627. indices.push(i * stride + nextJ);
  28628. indices.push(nextI * stride + nextJ);
  28629. indices.push(nextI * stride + j);
  28630. }
  28631. }
  28632. // Sides
  28633. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28634. // Result
  28635. var vertexData = new VertexData();
  28636. vertexData.indices = indices;
  28637. vertexData.positions = positions;
  28638. vertexData.normals = normals;
  28639. vertexData.uvs = uvs;
  28640. return vertexData;
  28641. };
  28642. VertexData.CreateLineSystem = function (options) {
  28643. var indices = [];
  28644. var positions = [];
  28645. var lines = options.lines;
  28646. var idx = 0;
  28647. for (var l = 0; l < lines.length; l++) {
  28648. var points = lines[l];
  28649. for (var index = 0; index < points.length; index++) {
  28650. positions.push(points[index].x, points[index].y, points[index].z);
  28651. if (index > 0) {
  28652. indices.push(idx - 1);
  28653. indices.push(idx);
  28654. }
  28655. idx++;
  28656. }
  28657. }
  28658. var vertexData = new VertexData();
  28659. vertexData.indices = indices;
  28660. vertexData.positions = positions;
  28661. return vertexData;
  28662. };
  28663. VertexData.CreateDashedLines = function (options) {
  28664. var dashSize = options.dashSize || 3;
  28665. var gapSize = options.gapSize || 1;
  28666. var dashNb = options.dashNb || 200;
  28667. var points = options.points;
  28668. var positions = new Array();
  28669. var indices = new Array();
  28670. var curvect = BABYLON.Vector3.Zero();
  28671. var lg = 0;
  28672. var nb = 0;
  28673. var shft = 0;
  28674. var dashshft = 0;
  28675. var curshft = 0;
  28676. var idx = 0;
  28677. var i = 0;
  28678. for (i = 0; i < points.length - 1; i++) {
  28679. points[i + 1].subtractToRef(points[i], curvect);
  28680. lg += curvect.length();
  28681. }
  28682. shft = lg / dashNb;
  28683. dashshft = dashSize * shft / (dashSize + gapSize);
  28684. for (i = 0; i < points.length - 1; i++) {
  28685. points[i + 1].subtractToRef(points[i], curvect);
  28686. nb = Math.floor(curvect.length() / shft);
  28687. curvect.normalize();
  28688. for (var j = 0; j < nb; j++) {
  28689. curshft = shft * j;
  28690. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28691. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28692. indices.push(idx, idx + 1);
  28693. idx += 2;
  28694. }
  28695. }
  28696. // Result
  28697. var vertexData = new VertexData();
  28698. vertexData.positions = positions;
  28699. vertexData.indices = indices;
  28700. return vertexData;
  28701. };
  28702. VertexData.CreateGround = function (options) {
  28703. var indices = [];
  28704. var positions = [];
  28705. var normals = [];
  28706. var uvs = [];
  28707. var row, col;
  28708. var width = options.width || 1;
  28709. var height = options.height || 1;
  28710. var subdivisions = options.subdivisions || 1;
  28711. for (row = 0; row <= subdivisions; row++) {
  28712. for (col = 0; col <= subdivisions; col++) {
  28713. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28714. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28715. positions.push(position.x, position.y, position.z);
  28716. normals.push(normal.x, normal.y, normal.z);
  28717. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28718. }
  28719. }
  28720. for (row = 0; row < subdivisions; row++) {
  28721. for (col = 0; col < subdivisions; col++) {
  28722. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28723. indices.push(col + 1 + row * (subdivisions + 1));
  28724. indices.push(col + row * (subdivisions + 1));
  28725. indices.push(col + (row + 1) * (subdivisions + 1));
  28726. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28727. indices.push(col + row * (subdivisions + 1));
  28728. }
  28729. }
  28730. // Result
  28731. var vertexData = new VertexData();
  28732. vertexData.indices = indices;
  28733. vertexData.positions = positions;
  28734. vertexData.normals = normals;
  28735. vertexData.uvs = uvs;
  28736. return vertexData;
  28737. };
  28738. VertexData.CreateTiledGround = function (options) {
  28739. var xmin = options.xmin;
  28740. var zmin = options.zmin;
  28741. var xmax = options.xmax;
  28742. var zmax = options.zmax;
  28743. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28744. var precision = options.precision || { w: 1, h: 1 };
  28745. var indices = [];
  28746. var positions = [];
  28747. var normals = [];
  28748. var uvs = [];
  28749. var row, col, tileRow, tileCol;
  28750. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28751. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28752. precision.w = (precision.w < 1) ? 1 : precision.w;
  28753. precision.h = (precision.h < 1) ? 1 : precision.h;
  28754. var tileSize = {
  28755. 'w': (xmax - xmin) / subdivisions.w,
  28756. 'h': (zmax - zmin) / subdivisions.h
  28757. };
  28758. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28759. // Indices
  28760. var base = positions.length / 3;
  28761. var rowLength = precision.w + 1;
  28762. for (row = 0; row < precision.h; row++) {
  28763. for (col = 0; col < precision.w; col++) {
  28764. var square = [
  28765. base + col + row * rowLength,
  28766. base + (col + 1) + row * rowLength,
  28767. base + (col + 1) + (row + 1) * rowLength,
  28768. base + col + (row + 1) * rowLength
  28769. ];
  28770. indices.push(square[1]);
  28771. indices.push(square[2]);
  28772. indices.push(square[3]);
  28773. indices.push(square[0]);
  28774. indices.push(square[1]);
  28775. indices.push(square[3]);
  28776. }
  28777. }
  28778. // Position, normals and uvs
  28779. var position = BABYLON.Vector3.Zero();
  28780. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28781. for (row = 0; row <= precision.h; row++) {
  28782. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28783. for (col = 0; col <= precision.w; col++) {
  28784. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28785. position.y = 0;
  28786. positions.push(position.x, position.y, position.z);
  28787. normals.push(normal.x, normal.y, normal.z);
  28788. uvs.push(col / precision.w, row / precision.h);
  28789. }
  28790. }
  28791. }
  28792. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28793. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28794. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28795. }
  28796. }
  28797. // Result
  28798. var vertexData = new VertexData();
  28799. vertexData.indices = indices;
  28800. vertexData.positions = positions;
  28801. vertexData.normals = normals;
  28802. vertexData.uvs = uvs;
  28803. return vertexData;
  28804. };
  28805. VertexData.CreateGroundFromHeightMap = function (options) {
  28806. var indices = [];
  28807. var positions = [];
  28808. var normals = [];
  28809. var uvs = [];
  28810. var row, col;
  28811. // Vertices
  28812. for (row = 0; row <= options.subdivisions; row++) {
  28813. for (col = 0; col <= options.subdivisions; col++) {
  28814. 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));
  28815. // Compute height
  28816. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28817. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28818. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28819. var r = options.buffer[pos] / 255.0;
  28820. var g = options.buffer[pos + 1] / 255.0;
  28821. var b = options.buffer[pos + 2] / 255.0;
  28822. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28823. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28824. // Add vertex
  28825. positions.push(position.x, position.y, position.z);
  28826. normals.push(0, 0, 0);
  28827. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28828. }
  28829. }
  28830. // Indices
  28831. for (row = 0; row < options.subdivisions; row++) {
  28832. for (col = 0; col < options.subdivisions; col++) {
  28833. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28834. indices.push(col + 1 + row * (options.subdivisions + 1));
  28835. indices.push(col + row * (options.subdivisions + 1));
  28836. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28837. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28838. indices.push(col + row * (options.subdivisions + 1));
  28839. }
  28840. }
  28841. // Normals
  28842. VertexData.ComputeNormals(positions, indices, normals);
  28843. // Result
  28844. var vertexData = new VertexData();
  28845. vertexData.indices = indices;
  28846. vertexData.positions = positions;
  28847. vertexData.normals = normals;
  28848. vertexData.uvs = uvs;
  28849. return vertexData;
  28850. };
  28851. VertexData.CreatePlane = function (options) {
  28852. var indices = [];
  28853. var positions = [];
  28854. var normals = [];
  28855. var uvs = [];
  28856. var width = options.width || options.size || 1;
  28857. var height = options.height || options.size || 1;
  28858. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28859. // Vertices
  28860. var halfWidth = width / 2.0;
  28861. var halfHeight = height / 2.0;
  28862. positions.push(-halfWidth, -halfHeight, 0);
  28863. normals.push(0, 0, -1.0);
  28864. uvs.push(0.0, 0.0);
  28865. positions.push(halfWidth, -halfHeight, 0);
  28866. normals.push(0, 0, -1.0);
  28867. uvs.push(1.0, 0.0);
  28868. positions.push(halfWidth, halfHeight, 0);
  28869. normals.push(0, 0, -1.0);
  28870. uvs.push(1.0, 1.0);
  28871. positions.push(-halfWidth, halfHeight, 0);
  28872. normals.push(0, 0, -1.0);
  28873. uvs.push(0.0, 1.0);
  28874. // Indices
  28875. indices.push(0);
  28876. indices.push(1);
  28877. indices.push(2);
  28878. indices.push(0);
  28879. indices.push(2);
  28880. indices.push(3);
  28881. // Sides
  28882. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28883. // Result
  28884. var vertexData = new VertexData();
  28885. vertexData.indices = indices;
  28886. vertexData.positions = positions;
  28887. vertexData.normals = normals;
  28888. vertexData.uvs = uvs;
  28889. return vertexData;
  28890. };
  28891. VertexData.CreateDisc = function (options) {
  28892. var positions = [];
  28893. var indices = [];
  28894. var normals = [];
  28895. var uvs = [];
  28896. var radius = options.radius || 0.5;
  28897. var tessellation = options.tessellation || 64;
  28898. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28899. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28900. // positions and uvs
  28901. positions.push(0, 0, 0); // disc center first
  28902. uvs.push(0.5, 0.5);
  28903. var theta = Math.PI * 2 * arc;
  28904. var step = theta / tessellation;
  28905. for (var a = 0; a < theta; a += step) {
  28906. var x = Math.cos(a);
  28907. var y = Math.sin(a);
  28908. var u = (x + 1) / 2;
  28909. var v = (1 - y) / 2;
  28910. positions.push(radius * x, radius * y, 0);
  28911. uvs.push(u, v);
  28912. }
  28913. if (arc === 1) {
  28914. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28915. uvs.push(uvs[2], uvs[3]);
  28916. }
  28917. //indices
  28918. var vertexNb = positions.length / 3;
  28919. for (var i = 1; i < vertexNb - 1; i++) {
  28920. indices.push(i + 1, 0, i);
  28921. }
  28922. // result
  28923. VertexData.ComputeNormals(positions, indices, normals);
  28924. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28925. var vertexData = new VertexData();
  28926. vertexData.indices = indices;
  28927. vertexData.positions = positions;
  28928. vertexData.normals = normals;
  28929. vertexData.uvs = uvs;
  28930. return vertexData;
  28931. };
  28932. VertexData.CreateIcoSphere = function (options) {
  28933. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28934. var radius = options.radius || 1;
  28935. var flat = (options.flat === undefined) ? true : options.flat;
  28936. var subdivisions = options.subdivisions || 4;
  28937. var radiusX = options.radiusX || radius;
  28938. var radiusY = options.radiusY || radius;
  28939. var radiusZ = options.radiusZ || radius;
  28940. var t = (1 + Math.sqrt(5)) / 2;
  28941. // 12 vertex x,y,z
  28942. var ico_vertices = [
  28943. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28944. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28945. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28946. ];
  28947. // index of 3 vertex makes a face of icopshere
  28948. var ico_indices = [
  28949. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28950. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28951. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28952. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28953. ];
  28954. // vertex for uv have aliased position, not for UV
  28955. var vertices_unalias_id = [
  28956. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28957. // vertex alias
  28958. 0,
  28959. 2,
  28960. 3,
  28961. 3,
  28962. 3,
  28963. 4,
  28964. 7,
  28965. 8,
  28966. 9,
  28967. 9,
  28968. 10,
  28969. 11 // 23: B + 12
  28970. ];
  28971. // uv as integer step (not pixels !)
  28972. var ico_vertexuv = [
  28973. 5, 1, 3, 1, 6, 4, 0, 0,
  28974. 5, 3, 4, 2, 2, 2, 4, 0,
  28975. 2, 0, 1, 1, 6, 0, 6, 2,
  28976. // vertex alias (for same vertex on different faces)
  28977. 0, 4,
  28978. 3, 3,
  28979. 4, 4,
  28980. 3, 1,
  28981. 4, 2,
  28982. 4, 4,
  28983. 0, 2,
  28984. 1, 1,
  28985. 2, 2,
  28986. 3, 3,
  28987. 1, 3,
  28988. 2, 4 // 23: B + 12
  28989. ];
  28990. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28991. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28992. // First island of uv mapping
  28993. // v = 4h 3+ 2
  28994. // v = 3h 9+ 4
  28995. // v = 2h 9+ 5 B
  28996. // v = 1h 9 1 0
  28997. // v = 0h 3 8 7 A
  28998. // u = 0 1 2 3 4 5 6 *a
  28999. // Second island of uv mapping
  29000. // v = 4h 0+ B+ 4+
  29001. // v = 3h A+ 2+
  29002. // v = 2h 7+ 6 3+
  29003. // v = 1h 8+ 3+
  29004. // v = 0h
  29005. // u = 0 1 2 3 4 5 6 *a
  29006. // Face layout on texture UV mapping
  29007. // ============
  29008. // \ 4 /\ 16 / ======
  29009. // \ / \ / /\ 11 /
  29010. // \/ 7 \/ / \ /
  29011. // ======= / 10 \/
  29012. // /\ 17 /\ =======
  29013. // / \ / \ \ 15 /\
  29014. // / 8 \/ 12 \ \ / \
  29015. // ============ \/ 6 \
  29016. // \ 18 /\ ============
  29017. // \ / \ \ 5 /\ 0 /
  29018. // \/ 13 \ \ / \ /
  29019. // ======= \/ 1 \/
  29020. // =============
  29021. // /\ 19 /\ 2 /\
  29022. // / \ / \ / \
  29023. // / 14 \/ 9 \/ 3 \
  29024. // ===================
  29025. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29026. var ustep = 138 / 1024;
  29027. var vstep = 239 / 1024;
  29028. var uoffset = 60 / 1024;
  29029. var voffset = 26 / 1024;
  29030. // Second island should have margin, not to touch the first island
  29031. // avoid any borderline artefact in pixel rounding
  29032. var island_u_offset = -40 / 1024;
  29033. var island_v_offset = +20 / 1024;
  29034. // face is either island 0 or 1 :
  29035. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29036. var island = [
  29037. 0, 0, 0, 0, 1,
  29038. 0, 0, 1, 1, 0,
  29039. 0, 0, 1, 1, 0,
  29040. 0, 1, 1, 1, 0 // 15 - 19
  29041. ];
  29042. var indices = [];
  29043. var positions = [];
  29044. var normals = [];
  29045. var uvs = [];
  29046. var current_indice = 0;
  29047. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29048. var face_vertex_pos = new Array(3);
  29049. var face_vertex_uv = new Array(3);
  29050. var v012;
  29051. for (v012 = 0; v012 < 3; v012++) {
  29052. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29053. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29054. }
  29055. // create all with normals
  29056. for (var face = 0; face < 20; face++) {
  29057. // 3 vertex per face
  29058. for (v012 = 0; v012 < 3; v012++) {
  29059. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29060. var v_id = ico_indices[3 * face + v012];
  29061. // vertex have 3D position (x,y,z)
  29062. 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]);
  29063. // Normalize to get normal, then scale to radius
  29064. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29065. // uv Coordinates from vertex ID
  29066. 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);
  29067. }
  29068. // Subdivide the face (interpolate pos, norm, uv)
  29069. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29070. // - norm is linear interpolation of vertex corner normal
  29071. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29072. // - uv is linear interpolation
  29073. //
  29074. // Topology is as below for sub-divide by 2
  29075. // vertex shown as v0,v1,v2
  29076. // interp index is i1 to progress in range [v0,v1[
  29077. // interp index is i2 to progress in range [v0,v2[
  29078. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29079. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29080. //
  29081. //
  29082. // i2 v2
  29083. // ^ ^
  29084. // / / \
  29085. // / / \
  29086. // / / \
  29087. // / / (0,1) \
  29088. // / #---------\
  29089. // / / \ (0,0)'/ \
  29090. // / / \ / \
  29091. // / / \ / \
  29092. // / / (0,0) \ / (1,0) \
  29093. // / #---------#---------\
  29094. // v0 v1
  29095. //
  29096. // --------------------> i1
  29097. //
  29098. // interp of (i1,i2):
  29099. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29100. // along i1 : lerp(x0,x1, i1/(S-i2))
  29101. //
  29102. // centroid of triangle is needed to get help normal computation
  29103. // (c1,c2) are used for centroid location
  29104. var interp_vertex = function (i1, i2, c1, c2) {
  29105. // vertex is interpolated from
  29106. // - face_vertex_pos[0..2]
  29107. // - face_vertex_uv[0..2]
  29108. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29109. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29110. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29111. pos_interp.normalize();
  29112. var vertex_normal;
  29113. if (flat) {
  29114. // in flat mode, recalculate normal as face centroid normal
  29115. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29116. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29117. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29118. }
  29119. else {
  29120. // in smooth mode, recalculate normal from each single vertex position
  29121. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29122. }
  29123. // Vertex normal need correction due to X,Y,Z radius scaling
  29124. vertex_normal.x /= radiusX;
  29125. vertex_normal.y /= radiusY;
  29126. vertex_normal.z /= radiusZ;
  29127. vertex_normal.normalize();
  29128. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29129. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29130. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29131. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29132. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29133. uvs.push(uv_interp.x, uv_interp.y);
  29134. // push each vertex has member of a face
  29135. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29136. indices.push(current_indice);
  29137. current_indice++;
  29138. };
  29139. for (var i2 = 0; i2 < subdivisions; i2++) {
  29140. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29141. // face : (i1,i2) for /\ :
  29142. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29143. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29144. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29145. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29146. if (i1 + i2 + 1 < subdivisions) {
  29147. // face : (i1,i2)' for \/ :
  29148. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29149. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29150. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29151. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29152. }
  29153. }
  29154. }
  29155. }
  29156. // Sides
  29157. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29158. // Result
  29159. var vertexData = new VertexData();
  29160. vertexData.indices = indices;
  29161. vertexData.positions = positions;
  29162. vertexData.normals = normals;
  29163. vertexData.uvs = uvs;
  29164. return vertexData;
  29165. };
  29166. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29167. VertexData.CreatePolyhedron = function (options) {
  29168. // provided polyhedron types :
  29169. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29170. // 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)
  29171. var polyhedra = [];
  29172. 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]] };
  29173. 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]] };
  29174. polyhedra[2] = {
  29175. 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]],
  29176. 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]]
  29177. };
  29178. polyhedra[3] = {
  29179. 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]],
  29180. 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]]
  29181. };
  29182. polyhedra[4] = {
  29183. 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]],
  29184. 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]]
  29185. };
  29186. 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]] };
  29187. 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]] };
  29188. 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]] };
  29189. 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]] };
  29190. 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]] };
  29191. 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]] };
  29192. 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]] };
  29193. 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]] };
  29194. 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]] };
  29195. polyhedra[14] = {
  29196. 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]],
  29197. 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]]
  29198. };
  29199. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29200. var size = options.size;
  29201. var sizeX = options.sizeX || size || 1;
  29202. var sizeY = options.sizeY || size || 1;
  29203. var sizeZ = options.sizeZ || size || 1;
  29204. var data = options.custom || polyhedra[type];
  29205. var nbfaces = data.face.length;
  29206. var faceUV = options.faceUV || new Array(nbfaces);
  29207. var faceColors = options.faceColors;
  29208. var flat = (options.flat === undefined) ? true : options.flat;
  29209. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29210. var positions = [];
  29211. var indices = [];
  29212. var normals = [];
  29213. var uvs = [];
  29214. var colors = [];
  29215. var index = 0;
  29216. var faceIdx = 0; // face cursor in the array "indexes"
  29217. var indexes = [];
  29218. var i = 0;
  29219. var f = 0;
  29220. var u, v, ang, x, y, tmp;
  29221. // default face colors and UV if undefined
  29222. if (flat) {
  29223. for (f = 0; f < nbfaces; f++) {
  29224. if (faceColors && faceColors[f] === undefined) {
  29225. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29226. }
  29227. if (faceUV && faceUV[f] === undefined) {
  29228. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29229. }
  29230. }
  29231. }
  29232. if (!flat) {
  29233. for (i = 0; i < data.vertex.length; i++) {
  29234. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29235. uvs.push(0, 0);
  29236. }
  29237. for (f = 0; f < nbfaces; f++) {
  29238. for (i = 0; i < data.face[f].length - 2; i++) {
  29239. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29240. }
  29241. }
  29242. }
  29243. else {
  29244. for (f = 0; f < nbfaces; f++) {
  29245. var fl = data.face[f].length; // number of vertices of the current face
  29246. ang = 2 * Math.PI / fl;
  29247. x = 0.5 * Math.tan(ang / 2);
  29248. y = 0.5;
  29249. // positions, uvs, colors
  29250. for (i = 0; i < fl; i++) {
  29251. // positions
  29252. 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);
  29253. indexes.push(index);
  29254. index++;
  29255. // uvs
  29256. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29257. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29258. uvs.push(u, v);
  29259. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29260. y = x * Math.sin(ang) + y * Math.cos(ang);
  29261. x = tmp;
  29262. // colors
  29263. if (faceColors) {
  29264. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29265. }
  29266. }
  29267. // indices from indexes
  29268. for (i = 0; i < fl - 2; i++) {
  29269. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29270. }
  29271. faceIdx += fl;
  29272. }
  29273. }
  29274. VertexData.ComputeNormals(positions, indices, normals);
  29275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29276. var vertexData = new VertexData();
  29277. vertexData.positions = positions;
  29278. vertexData.indices = indices;
  29279. vertexData.normals = normals;
  29280. vertexData.uvs = uvs;
  29281. if (faceColors && flat) {
  29282. vertexData.colors = colors;
  29283. }
  29284. return vertexData;
  29285. };
  29286. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29287. VertexData.CreateTorusKnot = function (options) {
  29288. var indices = [];
  29289. var positions = [];
  29290. var normals = [];
  29291. var uvs = [];
  29292. var radius = options.radius || 2;
  29293. var tube = options.tube || 0.5;
  29294. var radialSegments = options.radialSegments || 32;
  29295. var tubularSegments = options.tubularSegments || 32;
  29296. var p = options.p || 2;
  29297. var q = options.q || 3;
  29298. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29299. // Helper
  29300. var getPos = function (angle) {
  29301. var cu = Math.cos(angle);
  29302. var su = Math.sin(angle);
  29303. var quOverP = q / p * angle;
  29304. var cs = Math.cos(quOverP);
  29305. var tx = radius * (2 + cs) * 0.5 * cu;
  29306. var ty = radius * (2 + cs) * su * 0.5;
  29307. var tz = radius * Math.sin(quOverP) * 0.5;
  29308. return new BABYLON.Vector3(tx, ty, tz);
  29309. };
  29310. // Vertices
  29311. var i;
  29312. var j;
  29313. for (i = 0; i <= radialSegments; i++) {
  29314. var modI = i % radialSegments;
  29315. var u = modI / radialSegments * 2 * p * Math.PI;
  29316. var p1 = getPos(u);
  29317. var p2 = getPos(u + 0.01);
  29318. var tang = p2.subtract(p1);
  29319. var n = p2.add(p1);
  29320. var bitan = BABYLON.Vector3.Cross(tang, n);
  29321. n = BABYLON.Vector3.Cross(bitan, tang);
  29322. bitan.normalize();
  29323. n.normalize();
  29324. for (j = 0; j < tubularSegments; j++) {
  29325. var modJ = j % tubularSegments;
  29326. var v = modJ / tubularSegments * 2 * Math.PI;
  29327. var cx = -tube * Math.cos(v);
  29328. var cy = tube * Math.sin(v);
  29329. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29330. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29331. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29332. uvs.push(i / radialSegments);
  29333. uvs.push(j / tubularSegments);
  29334. }
  29335. }
  29336. for (i = 0; i < radialSegments; i++) {
  29337. for (j = 0; j < tubularSegments; j++) {
  29338. var jNext = (j + 1) % tubularSegments;
  29339. var a = i * tubularSegments + j;
  29340. var b = (i + 1) * tubularSegments + j;
  29341. var c = (i + 1) * tubularSegments + jNext;
  29342. var d = i * tubularSegments + jNext;
  29343. indices.push(d);
  29344. indices.push(b);
  29345. indices.push(a);
  29346. indices.push(d);
  29347. indices.push(c);
  29348. indices.push(b);
  29349. }
  29350. }
  29351. // Normals
  29352. VertexData.ComputeNormals(positions, indices, normals);
  29353. // Sides
  29354. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29355. // Result
  29356. var vertexData = new VertexData();
  29357. vertexData.indices = indices;
  29358. vertexData.positions = positions;
  29359. vertexData.normals = normals;
  29360. vertexData.uvs = uvs;
  29361. return vertexData;
  29362. };
  29363. // Tools
  29364. /**
  29365. * @param {any} - positions (number[] or Float32Array)
  29366. * @param {any} - indices (number[] or Uint16Array)
  29367. * @param {any} - normals (number[] or Float32Array)
  29368. */
  29369. VertexData.ComputeNormals = function (positions, indices, normals) {
  29370. var index = 0;
  29371. var p1p2x = 0.0;
  29372. var p1p2y = 0.0;
  29373. var p1p2z = 0.0;
  29374. var p3p2x = 0.0;
  29375. var p3p2y = 0.0;
  29376. var p3p2z = 0.0;
  29377. var faceNormalx = 0.0;
  29378. var faceNormaly = 0.0;
  29379. var faceNormalz = 0.0;
  29380. var length = 0.0;
  29381. var i1 = 0;
  29382. var i2 = 0;
  29383. var i3 = 0;
  29384. for (index = 0; index < positions.length; index++) {
  29385. normals[index] = 0.0;
  29386. }
  29387. // indice triplet = 1 face
  29388. var nbFaces = indices.length / 3;
  29389. for (index = 0; index < nbFaces; index++) {
  29390. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29391. i2 = indices[index * 3 + 1];
  29392. i3 = indices[index * 3 + 2];
  29393. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29394. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29395. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29396. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29397. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29398. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29399. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29400. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29401. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29402. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29403. length = (length === 0) ? 1.0 : length;
  29404. faceNormalx /= length; // normalize this normal
  29405. faceNormaly /= length;
  29406. faceNormalz /= length;
  29407. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29408. normals[i1 * 3 + 1] += faceNormaly;
  29409. normals[i1 * 3 + 2] += faceNormalz;
  29410. normals[i2 * 3] += faceNormalx;
  29411. normals[i2 * 3 + 1] += faceNormaly;
  29412. normals[i2 * 3 + 2] += faceNormalz;
  29413. normals[i3 * 3] += faceNormalx;
  29414. normals[i3 * 3 + 1] += faceNormaly;
  29415. normals[i3 * 3 + 2] += faceNormalz;
  29416. }
  29417. // last normalization of each normal
  29418. for (index = 0; index < normals.length / 3; index++) {
  29419. faceNormalx = normals[index * 3];
  29420. faceNormaly = normals[index * 3 + 1];
  29421. faceNormalz = normals[index * 3 + 2];
  29422. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29423. length = (length === 0) ? 1.0 : length;
  29424. faceNormalx /= length;
  29425. faceNormaly /= length;
  29426. faceNormalz /= length;
  29427. normals[index * 3] = faceNormalx;
  29428. normals[index * 3 + 1] = faceNormaly;
  29429. normals[index * 3 + 2] = faceNormalz;
  29430. }
  29431. };
  29432. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29433. var li = indices.length;
  29434. var ln = normals.length;
  29435. var i;
  29436. var n;
  29437. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29438. switch (sideOrientation) {
  29439. case BABYLON.Mesh.FRONTSIDE:
  29440. // nothing changed
  29441. break;
  29442. case BABYLON.Mesh.BACKSIDE:
  29443. var tmp;
  29444. // indices
  29445. for (i = 0; i < li; i += 3) {
  29446. tmp = indices[i];
  29447. indices[i] = indices[i + 2];
  29448. indices[i + 2] = tmp;
  29449. }
  29450. // normals
  29451. for (n = 0; n < ln; n++) {
  29452. normals[n] = -normals[n];
  29453. }
  29454. break;
  29455. case BABYLON.Mesh.DOUBLESIDE:
  29456. // positions
  29457. var lp = positions.length;
  29458. var l = lp / 3;
  29459. for (var p = 0; p < lp; p++) {
  29460. positions[lp + p] = positions[p];
  29461. }
  29462. // indices
  29463. for (i = 0; i < li; i += 3) {
  29464. indices[i + li] = indices[i + 2] + l;
  29465. indices[i + 1 + li] = indices[i + 1] + l;
  29466. indices[i + 2 + li] = indices[i] + l;
  29467. }
  29468. // normals
  29469. for (n = 0; n < ln; n++) {
  29470. normals[ln + n] = -normals[n];
  29471. }
  29472. // uvs
  29473. var lu = uvs.length;
  29474. for (var u = 0; u < lu; u++) {
  29475. uvs[u + lu] = uvs[u];
  29476. }
  29477. break;
  29478. }
  29479. };
  29480. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29481. var vertexData = new VertexData();
  29482. // positions
  29483. var positions = parsedVertexData.positions;
  29484. if (positions) {
  29485. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29486. }
  29487. // normals
  29488. var normals = parsedVertexData.normals;
  29489. if (normals) {
  29490. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29491. }
  29492. // uvs
  29493. var uvs = parsedVertexData.uvs;
  29494. if (uvs) {
  29495. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29496. }
  29497. // uv2s
  29498. var uv2s = parsedVertexData.uv2s;
  29499. if (uv2s) {
  29500. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29501. }
  29502. // uv3s
  29503. var uv3s = parsedVertexData.uv3s;
  29504. if (uv3s) {
  29505. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29506. }
  29507. // uv4s
  29508. var uv4s = parsedVertexData.uv4s;
  29509. if (uv4s) {
  29510. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29511. }
  29512. // uv5s
  29513. var uv5s = parsedVertexData.uv5s;
  29514. if (uv5s) {
  29515. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29516. }
  29517. // uv6s
  29518. var uv6s = parsedVertexData.uv6s;
  29519. if (uv6s) {
  29520. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29521. }
  29522. // colors
  29523. var colors = parsedVertexData.colors;
  29524. if (colors) {
  29525. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29526. }
  29527. // matricesIndices
  29528. var matricesIndices = parsedVertexData.matricesIndices;
  29529. if (matricesIndices) {
  29530. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29531. }
  29532. // matricesWeights
  29533. var matricesWeights = parsedVertexData.matricesWeights;
  29534. if (matricesWeights) {
  29535. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29536. }
  29537. // indices
  29538. var indices = parsedVertexData.indices;
  29539. if (indices) {
  29540. vertexData.indices = indices;
  29541. }
  29542. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29543. };
  29544. return VertexData;
  29545. })();
  29546. BABYLON.VertexData = VertexData;
  29547. })(BABYLON || (BABYLON = {}));
  29548. var BABYLON;
  29549. (function (BABYLON) {
  29550. var Tags = (function () {
  29551. function Tags() {
  29552. }
  29553. Tags.EnableFor = function (obj) {
  29554. obj._tags = obj._tags || {};
  29555. obj.hasTags = function () {
  29556. return Tags.HasTags(obj);
  29557. };
  29558. obj.addTags = function (tagsString) {
  29559. return Tags.AddTagsTo(obj, tagsString);
  29560. };
  29561. obj.removeTags = function (tagsString) {
  29562. return Tags.RemoveTagsFrom(obj, tagsString);
  29563. };
  29564. obj.matchesTagsQuery = function (tagsQuery) {
  29565. return Tags.MatchesQuery(obj, tagsQuery);
  29566. };
  29567. };
  29568. Tags.DisableFor = function (obj) {
  29569. delete obj._tags;
  29570. delete obj.hasTags;
  29571. delete obj.addTags;
  29572. delete obj.removeTags;
  29573. delete obj.matchesTagsQuery;
  29574. };
  29575. Tags.HasTags = function (obj) {
  29576. if (!obj._tags) {
  29577. return false;
  29578. }
  29579. return !BABYLON.Tools.IsEmpty(obj._tags);
  29580. };
  29581. Tags.GetTags = function (obj, asString) {
  29582. if (asString === void 0) { asString = true; }
  29583. if (!obj._tags) {
  29584. return null;
  29585. }
  29586. if (asString) {
  29587. var tagsArray = [];
  29588. for (var tag in obj._tags) {
  29589. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29590. tagsArray.push(tag);
  29591. }
  29592. }
  29593. return tagsArray.join(" ");
  29594. }
  29595. else {
  29596. return obj._tags;
  29597. }
  29598. };
  29599. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29600. // a tag cannot start with '||', '&&', and '!'
  29601. // it cannot contain whitespaces
  29602. Tags.AddTagsTo = function (obj, tagsString) {
  29603. if (!tagsString) {
  29604. return;
  29605. }
  29606. if (typeof tagsString !== "string") {
  29607. return;
  29608. }
  29609. var tags = tagsString.split(" ");
  29610. for (var t in tags) {
  29611. Tags._AddTagTo(obj, tags[t]);
  29612. }
  29613. };
  29614. Tags._AddTagTo = function (obj, tag) {
  29615. tag = tag.trim();
  29616. if (tag === "" || tag === "true" || tag === "false") {
  29617. return;
  29618. }
  29619. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29620. return;
  29621. }
  29622. Tags.EnableFor(obj);
  29623. obj._tags[tag] = true;
  29624. };
  29625. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29626. if (!Tags.HasTags(obj)) {
  29627. return;
  29628. }
  29629. var tags = tagsString.split(" ");
  29630. for (var t in tags) {
  29631. Tags._RemoveTagFrom(obj, tags[t]);
  29632. }
  29633. };
  29634. Tags._RemoveTagFrom = function (obj, tag) {
  29635. delete obj._tags[tag];
  29636. };
  29637. Tags.MatchesQuery = function (obj, tagsQuery) {
  29638. if (tagsQuery === undefined) {
  29639. return true;
  29640. }
  29641. if (tagsQuery === "") {
  29642. return Tags.HasTags(obj);
  29643. }
  29644. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29645. };
  29646. return Tags;
  29647. })();
  29648. BABYLON.Tags = Tags;
  29649. })(BABYLON || (BABYLON = {}));
  29650. var BABYLON;
  29651. (function (BABYLON) {
  29652. var Internals;
  29653. (function (Internals) {
  29654. var AndOrNotEvaluator = (function () {
  29655. function AndOrNotEvaluator() {
  29656. }
  29657. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29658. if (!query.match(/\([^\(\)]*\)/g)) {
  29659. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29660. }
  29661. else {
  29662. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29663. // remove parenthesis
  29664. r = r.slice(1, r.length - 1);
  29665. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29666. });
  29667. }
  29668. if (query === "true") {
  29669. return true;
  29670. }
  29671. if (query === "false") {
  29672. return false;
  29673. }
  29674. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29675. };
  29676. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29677. evaluateCallback = evaluateCallback || (function (r) {
  29678. return r === "true" ? true : false;
  29679. });
  29680. var result;
  29681. var or = parenthesisContent.split("||");
  29682. for (var i in or) {
  29683. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29684. var and = ori.split("&&");
  29685. if (and.length > 1) {
  29686. for (var j = 0; j < and.length; ++j) {
  29687. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29688. if (andj !== "true" && andj !== "false") {
  29689. if (andj[0] === "!") {
  29690. result = !evaluateCallback(andj.substring(1));
  29691. }
  29692. else {
  29693. result = evaluateCallback(andj);
  29694. }
  29695. }
  29696. else {
  29697. result = andj === "true" ? true : false;
  29698. }
  29699. if (!result) {
  29700. ori = "false";
  29701. break;
  29702. }
  29703. }
  29704. }
  29705. if (result || ori === "true") {
  29706. result = true;
  29707. break;
  29708. }
  29709. // result equals false (or undefined)
  29710. if (ori !== "true" && ori !== "false") {
  29711. if (ori[0] === "!") {
  29712. result = !evaluateCallback(ori.substring(1));
  29713. }
  29714. else {
  29715. result = evaluateCallback(ori);
  29716. }
  29717. }
  29718. else {
  29719. result = ori === "true" ? true : false;
  29720. }
  29721. }
  29722. // the whole parenthesis scope is replaced by 'true' or 'false'
  29723. return result ? "true" : "false";
  29724. };
  29725. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29726. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29727. // remove whitespaces
  29728. r = r.replace(/[\s]/g, function () { return ""; });
  29729. return r.length % 2 ? "!" : "";
  29730. });
  29731. booleanString = booleanString.trim();
  29732. if (booleanString === "!true") {
  29733. booleanString = "false";
  29734. }
  29735. else if (booleanString === "!false") {
  29736. booleanString = "true";
  29737. }
  29738. return booleanString;
  29739. };
  29740. return AndOrNotEvaluator;
  29741. })();
  29742. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29743. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29744. })(BABYLON || (BABYLON = {}));
  29745. var BABYLON;
  29746. (function (BABYLON) {
  29747. var PostProcessRenderPass = (function () {
  29748. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29749. this._enabled = true;
  29750. this._refCount = 0;
  29751. this._name = name;
  29752. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29753. this.setRenderList(renderList);
  29754. this._renderTexture.onBeforeRender = beforeRender;
  29755. this._renderTexture.onAfterRender = afterRender;
  29756. this._scene = scene;
  29757. this._renderList = renderList;
  29758. }
  29759. // private
  29760. PostProcessRenderPass.prototype._incRefCount = function () {
  29761. if (this._refCount === 0) {
  29762. this._scene.customRenderTargets.push(this._renderTexture);
  29763. }
  29764. return ++this._refCount;
  29765. };
  29766. PostProcessRenderPass.prototype._decRefCount = function () {
  29767. this._refCount--;
  29768. if (this._refCount <= 0) {
  29769. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29770. }
  29771. return this._refCount;
  29772. };
  29773. PostProcessRenderPass.prototype._update = function () {
  29774. this.setRenderList(this._renderList);
  29775. };
  29776. // public
  29777. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29778. this._renderTexture.renderList = renderList;
  29779. };
  29780. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29781. return this._renderTexture;
  29782. };
  29783. return PostProcessRenderPass;
  29784. })();
  29785. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29786. })(BABYLON || (BABYLON = {}));
  29787. var BABYLON;
  29788. (function (BABYLON) {
  29789. var PostProcessRenderEffect = (function () {
  29790. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29791. this._engine = engine;
  29792. this._name = name;
  29793. this._singleInstance = singleInstance || true;
  29794. this._getPostProcess = getPostProcess;
  29795. this._cameras = [];
  29796. this._indicesForCamera = [];
  29797. this._postProcesses = {};
  29798. this._renderPasses = {};
  29799. this._renderEffectAsPasses = {};
  29800. }
  29801. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29802. get: function () {
  29803. for (var index in this._postProcesses) {
  29804. if (!this._postProcesses[index].isSupported) {
  29805. return false;
  29806. }
  29807. }
  29808. return true;
  29809. },
  29810. enumerable: true,
  29811. configurable: true
  29812. });
  29813. PostProcessRenderEffect.prototype._update = function () {
  29814. for (var renderPassName in this._renderPasses) {
  29815. this._renderPasses[renderPassName]._update();
  29816. }
  29817. };
  29818. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29819. this._renderPasses[renderPass._name] = renderPass;
  29820. this._linkParameters();
  29821. };
  29822. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29823. delete this._renderPasses[renderPass._name];
  29824. this._linkParameters();
  29825. };
  29826. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29827. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29828. this._linkParameters();
  29829. };
  29830. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29831. for (var renderPassName in this._renderPasses) {
  29832. if (renderPassName === passName) {
  29833. return this._renderPasses[passName];
  29834. }
  29835. }
  29836. };
  29837. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29838. this._renderPasses = {};
  29839. this._linkParameters();
  29840. };
  29841. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29842. var cameraKey;
  29843. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29844. for (var i = 0; i < _cam.length; i++) {
  29845. var camera = _cam[i];
  29846. var cameraName = camera.name;
  29847. if (this._singleInstance) {
  29848. cameraKey = 0;
  29849. }
  29850. else {
  29851. cameraKey = cameraName;
  29852. }
  29853. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29854. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29855. if (!this._indicesForCamera[cameraName]) {
  29856. this._indicesForCamera[cameraName] = [];
  29857. }
  29858. this._indicesForCamera[cameraName].push(index);
  29859. if (this._cameras.indexOf(camera) === -1) {
  29860. this._cameras[cameraName] = camera;
  29861. }
  29862. for (var passName in this._renderPasses) {
  29863. this._renderPasses[passName]._incRefCount();
  29864. }
  29865. }
  29866. this._linkParameters();
  29867. };
  29868. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29869. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29870. for (var i = 0; i < _cam.length; i++) {
  29871. var camera = _cam[i];
  29872. var cameraName = camera.name;
  29873. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29874. var index = this._cameras.indexOf(cameraName);
  29875. this._indicesForCamera.splice(index, 1);
  29876. this._cameras.splice(index, 1);
  29877. for (var passName in this._renderPasses) {
  29878. this._renderPasses[passName]._decRefCount();
  29879. }
  29880. }
  29881. };
  29882. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29883. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29884. for (var i = 0; i < _cam.length; i++) {
  29885. var camera = _cam[i];
  29886. var cameraName = camera.name;
  29887. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29888. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29889. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29890. }
  29891. }
  29892. for (var passName in this._renderPasses) {
  29893. this._renderPasses[passName]._incRefCount();
  29894. }
  29895. }
  29896. };
  29897. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29898. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29899. for (var i = 0; i < _cam.length; i++) {
  29900. var camera = _cam[i];
  29901. var cameraName = camera.Name;
  29902. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29903. for (var passName in this._renderPasses) {
  29904. this._renderPasses[passName]._decRefCount();
  29905. }
  29906. }
  29907. };
  29908. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29909. if (this._singleInstance) {
  29910. return this._postProcesses[0];
  29911. }
  29912. else {
  29913. return this._postProcesses[camera.name];
  29914. }
  29915. };
  29916. PostProcessRenderEffect.prototype._linkParameters = function () {
  29917. var _this = this;
  29918. for (var index in this._postProcesses) {
  29919. if (this.applyParameters) {
  29920. this.applyParameters(this._postProcesses[index]);
  29921. }
  29922. this._postProcesses[index].onBeforeRender = function (effect) {
  29923. _this._linkTextures(effect);
  29924. };
  29925. }
  29926. };
  29927. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29928. for (var renderPassName in this._renderPasses) {
  29929. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29930. }
  29931. for (var renderEffectName in this._renderEffectAsPasses) {
  29932. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29933. }
  29934. };
  29935. return PostProcessRenderEffect;
  29936. })();
  29937. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29938. })(BABYLON || (BABYLON = {}));
  29939. var BABYLON;
  29940. (function (BABYLON) {
  29941. var PostProcessRenderPipeline = (function () {
  29942. function PostProcessRenderPipeline(engine, name) {
  29943. this._engine = engine;
  29944. this._name = name;
  29945. this._renderEffects = {};
  29946. this._renderEffectsForIsolatedPass = {};
  29947. this._cameras = [];
  29948. }
  29949. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29950. get: function () {
  29951. for (var renderEffectName in this._renderEffects) {
  29952. if (!this._renderEffects[renderEffectName].isSupported) {
  29953. return false;
  29954. }
  29955. }
  29956. return true;
  29957. },
  29958. enumerable: true,
  29959. configurable: true
  29960. });
  29961. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29962. this._renderEffects[renderEffect._name] = renderEffect;
  29963. };
  29964. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29965. var renderEffects = this._renderEffects[renderEffectName];
  29966. if (!renderEffects) {
  29967. return;
  29968. }
  29969. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29970. };
  29971. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29972. var renderEffects = this._renderEffects[renderEffectName];
  29973. if (!renderEffects) {
  29974. return;
  29975. }
  29976. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29977. };
  29978. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29979. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29980. var indicesToDelete = [];
  29981. var i;
  29982. for (i = 0; i < _cam.length; i++) {
  29983. var camera = _cam[i];
  29984. var cameraName = camera.name;
  29985. if (this._cameras.indexOf(camera) === -1) {
  29986. this._cameras[cameraName] = camera;
  29987. }
  29988. else if (unique) {
  29989. indicesToDelete.push(i);
  29990. }
  29991. }
  29992. for (i = 0; i < indicesToDelete.length; i++) {
  29993. cameras.splice(indicesToDelete[i], 1);
  29994. }
  29995. for (var renderEffectName in this._renderEffects) {
  29996. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29997. }
  29998. };
  29999. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  30000. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30001. for (var renderEffectName in this._renderEffects) {
  30002. this._renderEffects[renderEffectName]._detachCameras(_cam);
  30003. }
  30004. for (var i = 0; i < _cam.length; i++) {
  30005. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  30006. }
  30007. };
  30008. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  30009. var _this = this;
  30010. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30011. var pass = null;
  30012. var renderEffectName;
  30013. for (renderEffectName in this._renderEffects) {
  30014. pass = this._renderEffects[renderEffectName].getPass(passName);
  30015. if (pass != null) {
  30016. break;
  30017. }
  30018. }
  30019. if (pass === null) {
  30020. return;
  30021. }
  30022. for (renderEffectName in this._renderEffects) {
  30023. this._renderEffects[renderEffectName]._disable(_cam);
  30024. }
  30025. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  30026. for (var i = 0; i < _cam.length; i++) {
  30027. var camera = _cam[i];
  30028. var cameraName = camera.name;
  30029. 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); });
  30030. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  30031. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  30032. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  30033. }
  30034. };
  30035. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  30036. var _this = this;
  30037. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  30038. for (var i = 0; i < _cam.length; i++) {
  30039. var camera = _cam[i];
  30040. var cameraName = camera.name;
  30041. 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); });
  30042. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  30043. }
  30044. for (var renderEffectName in this._renderEffects) {
  30045. this._renderEffects[renderEffectName]._enable(_cam);
  30046. }
  30047. };
  30048. PostProcessRenderPipeline.prototype._update = function () {
  30049. for (var renderEffectName in this._renderEffects) {
  30050. this._renderEffects[renderEffectName]._update();
  30051. }
  30052. for (var i = 0; i < this._cameras.length; i++) {
  30053. var cameraName = this._cameras[i].name;
  30054. if (this._renderEffectsForIsolatedPass[cameraName]) {
  30055. this._renderEffectsForIsolatedPass[cameraName]._update();
  30056. }
  30057. }
  30058. };
  30059. PostProcessRenderPipeline.prototype.dispose = function () {
  30060. // Must be implemented by children
  30061. };
  30062. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  30063. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  30064. return PostProcessRenderPipeline;
  30065. })();
  30066. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  30067. })(BABYLON || (BABYLON = {}));
  30068. var BABYLON;
  30069. (function (BABYLON) {
  30070. var PostProcessRenderPipelineManager = (function () {
  30071. function PostProcessRenderPipelineManager() {
  30072. this._renderPipelines = {};
  30073. }
  30074. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  30075. this._renderPipelines[renderPipeline._name] = renderPipeline;
  30076. };
  30077. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  30078. var renderPipeline = this._renderPipelines[renderPipelineName];
  30079. if (!renderPipeline) {
  30080. return;
  30081. }
  30082. renderPipeline._attachCameras(cameras, unique);
  30083. };
  30084. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  30085. var renderPipeline = this._renderPipelines[renderPipelineName];
  30086. if (!renderPipeline) {
  30087. return;
  30088. }
  30089. renderPipeline._detachCameras(cameras);
  30090. };
  30091. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30092. var renderPipeline = this._renderPipelines[renderPipelineName];
  30093. if (!renderPipeline) {
  30094. return;
  30095. }
  30096. renderPipeline._enableEffect(renderEffectName, cameras);
  30097. };
  30098. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  30099. var renderPipeline = this._renderPipelines[renderPipelineName];
  30100. if (!renderPipeline) {
  30101. return;
  30102. }
  30103. renderPipeline._disableEffect(renderEffectName, cameras);
  30104. };
  30105. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  30106. var renderPipeline = this._renderPipelines[renderPipelineName];
  30107. if (!renderPipeline) {
  30108. return;
  30109. }
  30110. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  30111. };
  30112. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  30113. var renderPipeline = this._renderPipelines[renderPipelineName];
  30114. if (!renderPipeline) {
  30115. return;
  30116. }
  30117. renderPipeline._disableDisplayOnlyPass(cameras);
  30118. };
  30119. PostProcessRenderPipelineManager.prototype.update = function () {
  30120. for (var renderPipelineName in this._renderPipelines) {
  30121. var pipeline = this._renderPipelines[renderPipelineName];
  30122. if (!pipeline.isSupported) {
  30123. pipeline.dispose();
  30124. delete this._renderPipelines[renderPipelineName];
  30125. }
  30126. else {
  30127. pipeline._update();
  30128. }
  30129. }
  30130. };
  30131. return PostProcessRenderPipelineManager;
  30132. })();
  30133. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  30134. })(BABYLON || (BABYLON = {}));
  30135. var BABYLON;
  30136. (function (BABYLON) {
  30137. var BoundingBoxRenderer = (function () {
  30138. function BoundingBoxRenderer(scene) {
  30139. this.frontColor = new BABYLON.Color3(1, 1, 1);
  30140. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  30141. this.showBackLines = true;
  30142. this.renderList = new BABYLON.SmartArray(32);
  30143. this._scene = scene;
  30144. }
  30145. BoundingBoxRenderer.prototype._prepareRessources = function () {
  30146. if (this._colorShader) {
  30147. return;
  30148. }
  30149. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  30150. attributes: ["position"],
  30151. uniforms: ["worldViewProjection", "color"]
  30152. });
  30153. var engine = this._scene.getEngine();
  30154. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  30155. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  30156. 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]);
  30157. };
  30158. BoundingBoxRenderer.prototype.reset = function () {
  30159. this.renderList.reset();
  30160. };
  30161. BoundingBoxRenderer.prototype.render = function () {
  30162. if (this.renderList.length === 0) {
  30163. return;
  30164. }
  30165. this._prepareRessources();
  30166. if (!this._colorShader.isReady()) {
  30167. return;
  30168. }
  30169. var engine = this._scene.getEngine();
  30170. engine.setDepthWrite(false);
  30171. this._colorShader._preBind();
  30172. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  30173. var boundingBox = this.renderList.data[boundingBoxIndex];
  30174. var min = boundingBox.minimum;
  30175. var max = boundingBox.maximum;
  30176. var diff = max.subtract(min);
  30177. var median = min.add(diff.scale(0.5));
  30178. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  30179. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  30180. .multiply(boundingBox.getWorldMatrix());
  30181. // VBOs
  30182. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  30183. if (this.showBackLines) {
  30184. // Back
  30185. engine.setDepthFunctionToGreaterOrEqual();
  30186. this._scene.resetCachedMaterial();
  30187. this._colorShader.setColor4("color", this.backColor.toColor4());
  30188. this._colorShader.bind(worldMatrix);
  30189. // Draw order
  30190. engine.draw(false, 0, 24);
  30191. }
  30192. // Front
  30193. engine.setDepthFunctionToLess();
  30194. this._scene.resetCachedMaterial();
  30195. this._colorShader.setColor4("color", this.frontColor.toColor4());
  30196. this._colorShader.bind(worldMatrix);
  30197. // Draw order
  30198. engine.draw(false, 0, 24);
  30199. }
  30200. this._colorShader.unbind();
  30201. engine.setDepthFunctionToLessOrEqual();
  30202. engine.setDepthWrite(true);
  30203. };
  30204. BoundingBoxRenderer.prototype.dispose = function () {
  30205. if (!this._colorShader) {
  30206. return;
  30207. }
  30208. this._colorShader.dispose();
  30209. this._vb.dispose();
  30210. this._scene.getEngine()._releaseBuffer(this._ib);
  30211. };
  30212. return BoundingBoxRenderer;
  30213. })();
  30214. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  30215. })(BABYLON || (BABYLON = {}));
  30216. var BABYLON;
  30217. (function (BABYLON) {
  30218. var Condition = (function () {
  30219. function Condition(actionManager) {
  30220. this._actionManager = actionManager;
  30221. }
  30222. Condition.prototype.isValid = function () {
  30223. return true;
  30224. };
  30225. Condition.prototype._getProperty = function (propertyPath) {
  30226. return this._actionManager._getProperty(propertyPath);
  30227. };
  30228. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  30229. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30230. };
  30231. Condition.prototype.serialize = function () {
  30232. };
  30233. Condition.prototype._serialize = function (serializedCondition) {
  30234. return {
  30235. type: 2,
  30236. children: [],
  30237. name: serializedCondition.name,
  30238. properties: serializedCondition.properties
  30239. };
  30240. };
  30241. return Condition;
  30242. })();
  30243. BABYLON.Condition = Condition;
  30244. var ValueCondition = (function (_super) {
  30245. __extends(ValueCondition, _super);
  30246. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  30247. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  30248. _super.call(this, actionManager);
  30249. this.propertyPath = propertyPath;
  30250. this.value = value;
  30251. this.operator = operator;
  30252. this._target = target;
  30253. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  30254. this._property = this._getProperty(this.propertyPath);
  30255. }
  30256. Object.defineProperty(ValueCondition, "IsEqual", {
  30257. get: function () {
  30258. return ValueCondition._IsEqual;
  30259. },
  30260. enumerable: true,
  30261. configurable: true
  30262. });
  30263. Object.defineProperty(ValueCondition, "IsDifferent", {
  30264. get: function () {
  30265. return ValueCondition._IsDifferent;
  30266. },
  30267. enumerable: true,
  30268. configurable: true
  30269. });
  30270. Object.defineProperty(ValueCondition, "IsGreater", {
  30271. get: function () {
  30272. return ValueCondition._IsGreater;
  30273. },
  30274. enumerable: true,
  30275. configurable: true
  30276. });
  30277. Object.defineProperty(ValueCondition, "IsLesser", {
  30278. get: function () {
  30279. return ValueCondition._IsLesser;
  30280. },
  30281. enumerable: true,
  30282. configurable: true
  30283. });
  30284. // Methods
  30285. ValueCondition.prototype.isValid = function () {
  30286. switch (this.operator) {
  30287. case ValueCondition.IsGreater:
  30288. return this._effectiveTarget[this._property] > this.value;
  30289. case ValueCondition.IsLesser:
  30290. return this._effectiveTarget[this._property] < this.value;
  30291. case ValueCondition.IsEqual:
  30292. case ValueCondition.IsDifferent:
  30293. var check;
  30294. if (this.value.equals) {
  30295. check = this.value.equals(this._effectiveTarget[this._property]);
  30296. }
  30297. else {
  30298. check = this.value === this._effectiveTarget[this._property];
  30299. }
  30300. return this.operator === ValueCondition.IsEqual ? check : !check;
  30301. }
  30302. return false;
  30303. };
  30304. ValueCondition.prototype.serialize = function () {
  30305. return this._serialize({
  30306. name: "ValueCondition",
  30307. properties: [
  30308. BABYLON.Action._GetTargetProperty(this._target),
  30309. { name: "propertyPath", value: this.propertyPath },
  30310. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  30311. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  30312. ]
  30313. });
  30314. };
  30315. ValueCondition.GetOperatorName = function (operator) {
  30316. switch (operator) {
  30317. case ValueCondition._IsEqual: return "IsEqual";
  30318. case ValueCondition._IsDifferent: return "IsDifferent";
  30319. case ValueCondition._IsGreater: return "IsGreater";
  30320. case ValueCondition._IsLesser: return "IsLesser";
  30321. default: return "";
  30322. }
  30323. };
  30324. // Statics
  30325. ValueCondition._IsEqual = 0;
  30326. ValueCondition._IsDifferent = 1;
  30327. ValueCondition._IsGreater = 2;
  30328. ValueCondition._IsLesser = 3;
  30329. return ValueCondition;
  30330. })(Condition);
  30331. BABYLON.ValueCondition = ValueCondition;
  30332. var PredicateCondition = (function (_super) {
  30333. __extends(PredicateCondition, _super);
  30334. function PredicateCondition(actionManager, predicate) {
  30335. _super.call(this, actionManager);
  30336. this.predicate = predicate;
  30337. }
  30338. PredicateCondition.prototype.isValid = function () {
  30339. return this.predicate();
  30340. };
  30341. return PredicateCondition;
  30342. })(Condition);
  30343. BABYLON.PredicateCondition = PredicateCondition;
  30344. var StateCondition = (function (_super) {
  30345. __extends(StateCondition, _super);
  30346. function StateCondition(actionManager, target, value) {
  30347. _super.call(this, actionManager);
  30348. this.value = value;
  30349. this._target = target;
  30350. }
  30351. // Methods
  30352. StateCondition.prototype.isValid = function () {
  30353. return this._target.state === this.value;
  30354. };
  30355. StateCondition.prototype.serialize = function () {
  30356. return this._serialize({
  30357. name: "StateCondition",
  30358. properties: [
  30359. BABYLON.Action._GetTargetProperty(this._target),
  30360. { name: "value", value: this.value }
  30361. ]
  30362. });
  30363. };
  30364. return StateCondition;
  30365. })(Condition);
  30366. BABYLON.StateCondition = StateCondition;
  30367. })(BABYLON || (BABYLON = {}));
  30368. var BABYLON;
  30369. (function (BABYLON) {
  30370. var Action = (function () {
  30371. function Action(triggerOptions, condition) {
  30372. this.triggerOptions = triggerOptions;
  30373. if (triggerOptions.parameter) {
  30374. this.trigger = triggerOptions.trigger;
  30375. this._triggerParameter = triggerOptions.parameter;
  30376. }
  30377. else {
  30378. this.trigger = triggerOptions;
  30379. }
  30380. this._nextActiveAction = this;
  30381. this._condition = condition;
  30382. }
  30383. // Methods
  30384. Action.prototype._prepare = function () {
  30385. };
  30386. Action.prototype.getTriggerParameter = function () {
  30387. return this._triggerParameter;
  30388. };
  30389. Action.prototype._executeCurrent = function (evt) {
  30390. if (this._nextActiveAction._condition) {
  30391. var condition = this._nextActiveAction._condition;
  30392. var currentRenderId = this._actionManager.getScene().getRenderId();
  30393. // We cache the current evaluation for the current frame
  30394. if (condition._evaluationId === currentRenderId) {
  30395. if (!condition._currentResult) {
  30396. return;
  30397. }
  30398. }
  30399. else {
  30400. condition._evaluationId = currentRenderId;
  30401. if (!condition.isValid()) {
  30402. condition._currentResult = false;
  30403. return;
  30404. }
  30405. condition._currentResult = true;
  30406. }
  30407. }
  30408. this._nextActiveAction.execute(evt);
  30409. this.skipToNextActiveAction();
  30410. };
  30411. Action.prototype.execute = function (evt) {
  30412. };
  30413. Action.prototype.skipToNextActiveAction = function () {
  30414. if (this._nextActiveAction._child) {
  30415. if (!this._nextActiveAction._child._actionManager) {
  30416. this._nextActiveAction._child._actionManager = this._actionManager;
  30417. }
  30418. this._nextActiveAction = this._nextActiveAction._child;
  30419. }
  30420. else {
  30421. this._nextActiveAction = this;
  30422. }
  30423. };
  30424. Action.prototype.then = function (action) {
  30425. this._child = action;
  30426. action._actionManager = this._actionManager;
  30427. action._prepare();
  30428. return action;
  30429. };
  30430. Action.prototype._getProperty = function (propertyPath) {
  30431. return this._actionManager._getProperty(propertyPath);
  30432. };
  30433. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30434. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30435. };
  30436. Action.prototype.serialize = function (parent) {
  30437. };
  30438. // Called by BABYLON.Action objects in serialize(...). Internal use
  30439. Action.prototype._serialize = function (serializedAction, parent) {
  30440. var serializationObject = {
  30441. type: 1,
  30442. children: [],
  30443. name: serializedAction.name,
  30444. properties: serializedAction.properties || []
  30445. };
  30446. // Serialize child
  30447. if (this._child) {
  30448. this._child.serialize(serializationObject);
  30449. }
  30450. // Check if "this" has a condition
  30451. if (this._condition) {
  30452. var serializedCondition = this._condition.serialize();
  30453. serializedCondition.children.push(serializationObject);
  30454. if (parent) {
  30455. parent.children.push(serializedCondition);
  30456. }
  30457. return serializedCondition;
  30458. }
  30459. if (parent) {
  30460. parent.children.push(serializationObject);
  30461. }
  30462. return serializationObject;
  30463. };
  30464. Action._SerializeValueAsString = function (value) {
  30465. if (typeof value === "number") {
  30466. return value.toString();
  30467. }
  30468. if (typeof value === "boolean") {
  30469. return value ? "true" : "false";
  30470. }
  30471. if (value instanceof BABYLON.Vector2) {
  30472. return value.x + ", " + value.y;
  30473. }
  30474. if (value instanceof BABYLON.Vector3) {
  30475. return value.x + ", " + value.y + ", " + value.z;
  30476. }
  30477. if (value instanceof BABYLON.Color3) {
  30478. return value.r + ", " + value.g + ", " + value.b;
  30479. }
  30480. if (value instanceof BABYLON.Color4) {
  30481. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  30482. }
  30483. return value; // string
  30484. };
  30485. Action._GetTargetProperty = function (target) {
  30486. return {
  30487. name: "target",
  30488. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  30489. : target instanceof BABYLON.Light ? "LightProperties"
  30490. : target instanceof BABYLON.Camera ? "CameraProperties"
  30491. : "SceneProperties",
  30492. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  30493. };
  30494. };
  30495. return Action;
  30496. })();
  30497. BABYLON.Action = Action;
  30498. })(BABYLON || (BABYLON = {}));
  30499. var BABYLON;
  30500. (function (BABYLON) {
  30501. /**
  30502. * ActionEvent is the event beint sent when an action is triggered.
  30503. */
  30504. var ActionEvent = (function () {
  30505. /**
  30506. * @constructor
  30507. * @param source The mesh or sprite that triggered the action.
  30508. * @param pointerX The X mouse cursor position at the time of the event
  30509. * @param pointerY The Y mouse cursor position at the time of the event
  30510. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30511. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30512. */
  30513. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30514. this.source = source;
  30515. this.pointerX = pointerX;
  30516. this.pointerY = pointerY;
  30517. this.meshUnderPointer = meshUnderPointer;
  30518. this.sourceEvent = sourceEvent;
  30519. this.additionalData = additionalData;
  30520. }
  30521. /**
  30522. * Helper function to auto-create an ActionEvent from a source mesh.
  30523. * @param source The source mesh that triggered the event
  30524. * @param evt {Event} The original (browser) event
  30525. */
  30526. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30527. var scene = source.getScene();
  30528. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30529. };
  30530. /**
  30531. * Helper function to auto-create an ActionEvent from a source mesh.
  30532. * @param source The source sprite that triggered the event
  30533. * @param scene Scene associated with the sprite
  30534. * @param evt {Event} The original (browser) event
  30535. */
  30536. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30537. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30538. };
  30539. /**
  30540. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30541. * @param scene the scene where the event occurred
  30542. * @param evt {Event} The original (browser) event
  30543. */
  30544. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30545. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30546. };
  30547. return ActionEvent;
  30548. })();
  30549. BABYLON.ActionEvent = ActionEvent;
  30550. /**
  30551. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30552. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30553. */
  30554. var ActionManager = (function () {
  30555. function ActionManager(scene) {
  30556. // Members
  30557. this.actions = new Array();
  30558. this._scene = scene;
  30559. scene._actionManagers.push(this);
  30560. }
  30561. Object.defineProperty(ActionManager, "NothingTrigger", {
  30562. get: function () {
  30563. return ActionManager._NothingTrigger;
  30564. },
  30565. enumerable: true,
  30566. configurable: true
  30567. });
  30568. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30569. get: function () {
  30570. return ActionManager._OnPickTrigger;
  30571. },
  30572. enumerable: true,
  30573. configurable: true
  30574. });
  30575. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30576. get: function () {
  30577. return ActionManager._OnLeftPickTrigger;
  30578. },
  30579. enumerable: true,
  30580. configurable: true
  30581. });
  30582. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30583. get: function () {
  30584. return ActionManager._OnRightPickTrigger;
  30585. },
  30586. enumerable: true,
  30587. configurable: true
  30588. });
  30589. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30590. get: function () {
  30591. return ActionManager._OnCenterPickTrigger;
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30597. get: function () {
  30598. return ActionManager._OnPickDownTrigger;
  30599. },
  30600. enumerable: true,
  30601. configurable: true
  30602. });
  30603. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30604. get: function () {
  30605. return ActionManager._OnPickUpTrigger;
  30606. },
  30607. enumerable: true,
  30608. configurable: true
  30609. });
  30610. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30611. /// This trigger will only be raised if you also declared a OnPickDown
  30612. get: function () {
  30613. return ActionManager._OnPickOutTrigger;
  30614. },
  30615. enumerable: true,
  30616. configurable: true
  30617. });
  30618. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30619. get: function () {
  30620. return ActionManager._OnLongPressTrigger;
  30621. },
  30622. enumerable: true,
  30623. configurable: true
  30624. });
  30625. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30626. get: function () {
  30627. return ActionManager._OnPointerOverTrigger;
  30628. },
  30629. enumerable: true,
  30630. configurable: true
  30631. });
  30632. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30633. get: function () {
  30634. return ActionManager._OnPointerOutTrigger;
  30635. },
  30636. enumerable: true,
  30637. configurable: true
  30638. });
  30639. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30640. get: function () {
  30641. return ActionManager._OnEveryFrameTrigger;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30647. get: function () {
  30648. return ActionManager._OnIntersectionEnterTrigger;
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30654. get: function () {
  30655. return ActionManager._OnIntersectionExitTrigger;
  30656. },
  30657. enumerable: true,
  30658. configurable: true
  30659. });
  30660. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30661. get: function () {
  30662. return ActionManager._OnKeyDownTrigger;
  30663. },
  30664. enumerable: true,
  30665. configurable: true
  30666. });
  30667. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30668. get: function () {
  30669. return ActionManager._OnKeyUpTrigger;
  30670. },
  30671. enumerable: true,
  30672. configurable: true
  30673. });
  30674. // Methods
  30675. ActionManager.prototype.dispose = function () {
  30676. var index = this._scene._actionManagers.indexOf(this);
  30677. if (index > -1) {
  30678. this._scene._actionManagers.splice(index, 1);
  30679. }
  30680. };
  30681. ActionManager.prototype.getScene = function () {
  30682. return this._scene;
  30683. };
  30684. /**
  30685. * Does this action manager handles actions of any of the given triggers
  30686. * @param {number[]} triggers - the triggers to be tested
  30687. * @return {boolean} whether one (or more) of the triggers is handeled
  30688. */
  30689. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30690. for (var index = 0; index < this.actions.length; index++) {
  30691. var action = this.actions[index];
  30692. if (triggers.indexOf(action.trigger) > -1) {
  30693. return true;
  30694. }
  30695. }
  30696. return false;
  30697. };
  30698. /**
  30699. * Does this action manager handles actions of a given trigger
  30700. * @param {number} trigger - the trigger to be tested
  30701. * @return {boolean} whether the trigger is handeled
  30702. */
  30703. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30704. for (var index = 0; index < this.actions.length; index++) {
  30705. var action = this.actions[index];
  30706. if (action.trigger === trigger) {
  30707. return true;
  30708. }
  30709. }
  30710. return false;
  30711. };
  30712. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30713. /**
  30714. * Does this action manager has pointer triggers
  30715. * @return {boolean} whether or not it has pointer triggers
  30716. */
  30717. get: function () {
  30718. for (var index = 0; index < this.actions.length; index++) {
  30719. var action = this.actions[index];
  30720. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30721. return true;
  30722. }
  30723. }
  30724. return false;
  30725. },
  30726. enumerable: true,
  30727. configurable: true
  30728. });
  30729. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30730. /**
  30731. * Does this action manager has pick triggers
  30732. * @return {boolean} whether or not it has pick triggers
  30733. */
  30734. get: function () {
  30735. for (var index = 0; index < this.actions.length; index++) {
  30736. var action = this.actions[index];
  30737. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30738. return true;
  30739. }
  30740. }
  30741. return false;
  30742. },
  30743. enumerable: true,
  30744. configurable: true
  30745. });
  30746. /**
  30747. * Registers an action to this action manager
  30748. * @param {BABYLON.Action} action - the action to be registered
  30749. * @return {BABYLON.Action} the action amended (prepared) after registration
  30750. */
  30751. ActionManager.prototype.registerAction = function (action) {
  30752. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30753. if (this.getScene().actionManager !== this) {
  30754. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30755. return null;
  30756. }
  30757. }
  30758. this.actions.push(action);
  30759. action._actionManager = this;
  30760. action._prepare();
  30761. return action;
  30762. };
  30763. /**
  30764. * Process a specific trigger
  30765. * @param {number} trigger - the trigger to process
  30766. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30767. */
  30768. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30769. for (var index = 0; index < this.actions.length; index++) {
  30770. var action = this.actions[index];
  30771. if (action.trigger === trigger) {
  30772. if (trigger === ActionManager.OnKeyUpTrigger
  30773. || trigger === ActionManager.OnKeyDownTrigger) {
  30774. var parameter = action.getTriggerParameter();
  30775. if (parameter) {
  30776. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30777. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30778. if (actualkey !== parameter.toLowerCase()) {
  30779. continue;
  30780. }
  30781. }
  30782. }
  30783. action._executeCurrent(evt);
  30784. }
  30785. }
  30786. };
  30787. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30788. var properties = propertyPath.split(".");
  30789. for (var index = 0; index < properties.length - 1; index++) {
  30790. target = target[properties[index]];
  30791. }
  30792. return target;
  30793. };
  30794. ActionManager.prototype._getProperty = function (propertyPath) {
  30795. var properties = propertyPath.split(".");
  30796. return properties[properties.length - 1];
  30797. };
  30798. ActionManager.prototype.serialize = function (name) {
  30799. var root = {
  30800. children: [],
  30801. name: name,
  30802. type: 3,
  30803. properties: [] // Empty for root but required
  30804. };
  30805. for (var i = 0; i < this.actions.length; i++) {
  30806. var triggerObject = {
  30807. type: 0,
  30808. children: [],
  30809. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  30810. properties: []
  30811. };
  30812. var triggerOptions = this.actions[i].triggerOptions;
  30813. if (triggerOptions && typeof triggerOptions !== "number") {
  30814. if (triggerOptions.parameter instanceof BABYLON.Node) {
  30815. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  30816. }
  30817. else {
  30818. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  30819. }
  30820. }
  30821. // Serialize child action, recursively
  30822. this.actions[i].serialize(triggerObject);
  30823. // Add serialized trigger
  30824. root.children.push(triggerObject);
  30825. }
  30826. return root;
  30827. };
  30828. ActionManager.Parse = function (parsedActions, object, scene) {
  30829. var actionManager = new BABYLON.ActionManager(scene);
  30830. if (object === null)
  30831. scene.actionManager = actionManager;
  30832. else
  30833. object.actionManager = actionManager;
  30834. // instanciate a new object
  30835. var instanciate = function (name, params) {
  30836. var newInstance = Object.create(BABYLON[name].prototype);
  30837. newInstance.constructor.apply(newInstance, params);
  30838. return newInstance;
  30839. };
  30840. var parseParameter = function (name, value, target, propertyPath) {
  30841. if (propertyPath === null) {
  30842. // String, boolean or float
  30843. var floatValue = parseFloat(value);
  30844. if (value === "true" || value === "false")
  30845. return value === "true";
  30846. else
  30847. return isNaN(floatValue) ? value : floatValue;
  30848. }
  30849. var effectiveTarget = propertyPath.split(".");
  30850. var values = value.split(",");
  30851. // Get effective Target
  30852. for (var i = 0; i < effectiveTarget.length; i++) {
  30853. target = target[effectiveTarget[i]];
  30854. }
  30855. // Return appropriate value with its type
  30856. if (typeof (target) === "boolean")
  30857. return values[0] === "true";
  30858. if (typeof (target) === "string")
  30859. return values[0];
  30860. // Parameters with multiple values such as Vector3 etc.
  30861. var split = new Array();
  30862. for (var i = 0; i < values.length; i++)
  30863. split.push(parseFloat(values[i]));
  30864. if (target instanceof BABYLON.Vector3)
  30865. return BABYLON.Vector3.FromArray(split);
  30866. if (target instanceof BABYLON.Vector4)
  30867. return BABYLON.Vector4.FromArray(split);
  30868. if (target instanceof BABYLON.Color3)
  30869. return BABYLON.Color3.FromArray(split);
  30870. if (target instanceof BABYLON.Color4)
  30871. return BABYLON.Color4.FromArray(split);
  30872. return parseFloat(values[0]);
  30873. };
  30874. // traverse graph per trigger
  30875. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30876. if (combineArray === void 0) { combineArray = null; }
  30877. if (parsedAction.detached)
  30878. return;
  30879. var parameters = new Array();
  30880. var target = null;
  30881. var propertyPath = null;
  30882. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30883. // Parameters
  30884. if (parsedAction.type === 2)
  30885. parameters.push(actionManager);
  30886. else
  30887. parameters.push(trigger);
  30888. if (combine) {
  30889. var actions = new Array();
  30890. for (var j = 0; j < parsedAction.combine.length; j++) {
  30891. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30892. }
  30893. parameters.push(actions);
  30894. }
  30895. else {
  30896. for (var i = 0; i < parsedAction.properties.length; i++) {
  30897. var value = parsedAction.properties[i].value;
  30898. var name = parsedAction.properties[i].name;
  30899. var targetType = parsedAction.properties[i].targetType;
  30900. if (name === "target")
  30901. if (targetType !== null && targetType === "SceneProperties")
  30902. value = target = scene;
  30903. else
  30904. value = target = scene.getNodeByName(value);
  30905. else if (name === "parent")
  30906. value = scene.getNodeByName(value);
  30907. else if (name === "sound")
  30908. value = scene.getSoundByName(value);
  30909. else if (name !== "propertyPath") {
  30910. if (parsedAction.type === 2 && name === "operator")
  30911. value = BABYLON.ValueCondition[value];
  30912. else
  30913. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30914. }
  30915. else {
  30916. propertyPath = value;
  30917. }
  30918. parameters.push(value);
  30919. }
  30920. }
  30921. if (combineArray === null) {
  30922. parameters.push(condition);
  30923. }
  30924. else {
  30925. parameters.push(null);
  30926. }
  30927. // If interpolate value action
  30928. if (parsedAction.name === "InterpolateValueAction") {
  30929. var param = parameters[parameters.length - 2];
  30930. parameters[parameters.length - 1] = param;
  30931. parameters[parameters.length - 2] = condition;
  30932. }
  30933. // Action or condition(s) and not CombineAction
  30934. var newAction = instanciate(parsedAction.name, parameters);
  30935. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30936. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30937. if (action)
  30938. action.then(nothing);
  30939. else
  30940. actionManager.registerAction(nothing);
  30941. action = nothing;
  30942. }
  30943. if (combineArray === null) {
  30944. if (newAction instanceof BABYLON.Condition) {
  30945. condition = newAction;
  30946. newAction = action;
  30947. }
  30948. else {
  30949. condition = null;
  30950. if (action)
  30951. action.then(newAction);
  30952. else
  30953. actionManager.registerAction(newAction);
  30954. }
  30955. }
  30956. else {
  30957. combineArray.push(newAction);
  30958. }
  30959. for (var i = 0; i < parsedAction.children.length; i++)
  30960. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30961. };
  30962. // triggers
  30963. for (var i = 0; i < parsedActions.children.length; i++) {
  30964. var triggerParams;
  30965. var trigger = parsedActions.children[i];
  30966. if (trigger.properties.length > 0) {
  30967. var param = trigger.properties[0].value;
  30968. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30969. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30970. }
  30971. else
  30972. triggerParams = BABYLON.ActionManager[trigger.name];
  30973. for (var j = 0; j < trigger.children.length; j++) {
  30974. if (!trigger.detached)
  30975. traverse(trigger.children[j], triggerParams, null, null);
  30976. }
  30977. }
  30978. };
  30979. ActionManager.GetTriggerName = function (trigger) {
  30980. switch (trigger) {
  30981. case 0: return "NothingTrigger";
  30982. case 1: return "OnPickTrigger";
  30983. case 2: return "OnLeftPickTrigger";
  30984. case 3: return "OnRightPickTrigger";
  30985. case 4: return "OnCenterPickTrigger";
  30986. case 5: return "OnPickDownTrigger";
  30987. case 6: return "OnPickUpTrigger";
  30988. case 7: return "OnLongPressTrigger";
  30989. case 8: return "OnPointerOverTrigger";
  30990. case 9: return "OnPointerOutTrigger";
  30991. case 10: return "OnEveryFrameTrigger";
  30992. case 11: return "OnIntersectionEnterTrigger";
  30993. case 12: return "OnIntersectionExitTrigger";
  30994. case 13: return "OnKeyDownTrigger";
  30995. case 14: return "OnKeyUpTrigger";
  30996. case 15: return "OnPickOutTrigger";
  30997. default: return "";
  30998. }
  30999. };
  31000. // Statics
  31001. ActionManager._NothingTrigger = 0;
  31002. ActionManager._OnPickTrigger = 1;
  31003. ActionManager._OnLeftPickTrigger = 2;
  31004. ActionManager._OnRightPickTrigger = 3;
  31005. ActionManager._OnCenterPickTrigger = 4;
  31006. ActionManager._OnPickDownTrigger = 5;
  31007. ActionManager._OnPickUpTrigger = 6;
  31008. ActionManager._OnLongPressTrigger = 7;
  31009. ActionManager._OnPointerOverTrigger = 8;
  31010. ActionManager._OnPointerOutTrigger = 9;
  31011. ActionManager._OnEveryFrameTrigger = 10;
  31012. ActionManager._OnIntersectionEnterTrigger = 11;
  31013. ActionManager._OnIntersectionExitTrigger = 12;
  31014. ActionManager._OnKeyDownTrigger = 13;
  31015. ActionManager._OnKeyUpTrigger = 14;
  31016. ActionManager._OnPickOutTrigger = 15;
  31017. ActionManager.DragMovementThreshold = 10; // in pixels
  31018. ActionManager.LongPressDelay = 500; // in milliseconds
  31019. return ActionManager;
  31020. })();
  31021. BABYLON.ActionManager = ActionManager;
  31022. })(BABYLON || (BABYLON = {}));
  31023. var BABYLON;
  31024. (function (BABYLON) {
  31025. var InterpolateValueAction = (function (_super) {
  31026. __extends(InterpolateValueAction, _super);
  31027. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  31028. if (duration === void 0) { duration = 1000; }
  31029. _super.call(this, triggerOptions, condition);
  31030. this.propertyPath = propertyPath;
  31031. this.value = value;
  31032. this.duration = duration;
  31033. this.stopOtherAnimations = stopOtherAnimations;
  31034. this.onInterpolationDone = onInterpolationDone;
  31035. this._target = this._effectiveTarget = target;
  31036. }
  31037. InterpolateValueAction.prototype._prepare = function () {
  31038. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31039. this._property = this._getProperty(this.propertyPath);
  31040. };
  31041. InterpolateValueAction.prototype.execute = function () {
  31042. var scene = this._actionManager.getScene();
  31043. var keys = [
  31044. {
  31045. frame: 0,
  31046. value: this._effectiveTarget[this._property]
  31047. }, {
  31048. frame: 100,
  31049. value: this.value
  31050. }
  31051. ];
  31052. var dataType;
  31053. if (typeof this.value === "number") {
  31054. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  31055. }
  31056. else if (this.value instanceof BABYLON.Color3) {
  31057. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  31058. }
  31059. else if (this.value instanceof BABYLON.Vector3) {
  31060. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  31061. }
  31062. else if (this.value instanceof BABYLON.Matrix) {
  31063. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  31064. }
  31065. else if (this.value instanceof BABYLON.Quaternion) {
  31066. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  31067. }
  31068. else {
  31069. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  31070. return;
  31071. }
  31072. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  31073. animation.setKeys(keys);
  31074. if (this.stopOtherAnimations) {
  31075. scene.stopAnimation(this._effectiveTarget);
  31076. }
  31077. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  31078. };
  31079. InterpolateValueAction.prototype.serialize = function (parent) {
  31080. return _super.prototype._serialize.call(this, {
  31081. name: "InterpolateValueAction",
  31082. properties: [
  31083. BABYLON.Action._GetTargetProperty(this._target),
  31084. { name: "propertyPath", value: this.propertyPath },
  31085. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  31086. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  31087. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  31088. ]
  31089. }, parent);
  31090. };
  31091. return InterpolateValueAction;
  31092. })(BABYLON.Action);
  31093. BABYLON.InterpolateValueAction = InterpolateValueAction;
  31094. })(BABYLON || (BABYLON = {}));
  31095. var BABYLON;
  31096. (function (BABYLON) {
  31097. var SwitchBooleanAction = (function (_super) {
  31098. __extends(SwitchBooleanAction, _super);
  31099. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  31100. _super.call(this, triggerOptions, condition);
  31101. this.propertyPath = propertyPath;
  31102. this._target = this._effectiveTarget = target;
  31103. }
  31104. SwitchBooleanAction.prototype._prepare = function () {
  31105. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31106. this._property = this._getProperty(this.propertyPath);
  31107. };
  31108. SwitchBooleanAction.prototype.execute = function () {
  31109. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  31110. };
  31111. SwitchBooleanAction.prototype.serialize = function (parent) {
  31112. return _super.prototype._serialize.call(this, {
  31113. name: "SwitchBooleanAction",
  31114. properties: [
  31115. BABYLON.Action._GetTargetProperty(this._target),
  31116. { name: "propertyPath", value: this.propertyPath }
  31117. ]
  31118. }, parent);
  31119. };
  31120. return SwitchBooleanAction;
  31121. })(BABYLON.Action);
  31122. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  31123. var SetStateAction = (function (_super) {
  31124. __extends(SetStateAction, _super);
  31125. function SetStateAction(triggerOptions, target, value, condition) {
  31126. _super.call(this, triggerOptions, condition);
  31127. this.value = value;
  31128. this._target = target;
  31129. }
  31130. SetStateAction.prototype.execute = function () {
  31131. this._target.state = this.value;
  31132. };
  31133. SetStateAction.prototype.serialize = function (parent) {
  31134. return _super.prototype._serialize.call(this, {
  31135. name: "SetStateAction",
  31136. properties: [
  31137. BABYLON.Action._GetTargetProperty(this._target),
  31138. { name: "value", value: this.value }
  31139. ]
  31140. }, parent);
  31141. };
  31142. return SetStateAction;
  31143. })(BABYLON.Action);
  31144. BABYLON.SetStateAction = SetStateAction;
  31145. var SetValueAction = (function (_super) {
  31146. __extends(SetValueAction, _super);
  31147. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  31148. _super.call(this, triggerOptions, condition);
  31149. this.propertyPath = propertyPath;
  31150. this.value = value;
  31151. this._target = this._effectiveTarget = target;
  31152. }
  31153. SetValueAction.prototype._prepare = function () {
  31154. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31155. this._property = this._getProperty(this.propertyPath);
  31156. };
  31157. SetValueAction.prototype.execute = function () {
  31158. this._effectiveTarget[this._property] = this.value;
  31159. };
  31160. SetValueAction.prototype.serialize = function (parent) {
  31161. return _super.prototype._serialize.call(this, {
  31162. name: "SetValueAction",
  31163. properties: [
  31164. BABYLON.Action._GetTargetProperty(this._target),
  31165. { name: "propertyPath", value: this.propertyPath },
  31166. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31167. ]
  31168. }, parent);
  31169. };
  31170. return SetValueAction;
  31171. })(BABYLON.Action);
  31172. BABYLON.SetValueAction = SetValueAction;
  31173. var IncrementValueAction = (function (_super) {
  31174. __extends(IncrementValueAction, _super);
  31175. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  31176. _super.call(this, triggerOptions, condition);
  31177. this.propertyPath = propertyPath;
  31178. this.value = value;
  31179. this._target = this._effectiveTarget = target;
  31180. }
  31181. IncrementValueAction.prototype._prepare = function () {
  31182. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  31183. this._property = this._getProperty(this.propertyPath);
  31184. if (typeof this._effectiveTarget[this._property] !== "number") {
  31185. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  31186. }
  31187. };
  31188. IncrementValueAction.prototype.execute = function () {
  31189. this._effectiveTarget[this._property] += this.value;
  31190. };
  31191. IncrementValueAction.prototype.serialize = function (parent) {
  31192. return _super.prototype._serialize.call(this, {
  31193. name: "IncrementValueAction",
  31194. properties: [
  31195. BABYLON.Action._GetTargetProperty(this._target),
  31196. { name: "propertyPath", value: this.propertyPath },
  31197. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  31198. ]
  31199. }, parent);
  31200. };
  31201. return IncrementValueAction;
  31202. })(BABYLON.Action);
  31203. BABYLON.IncrementValueAction = IncrementValueAction;
  31204. var PlayAnimationAction = (function (_super) {
  31205. __extends(PlayAnimationAction, _super);
  31206. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  31207. _super.call(this, triggerOptions, condition);
  31208. this.from = from;
  31209. this.to = to;
  31210. this.loop = loop;
  31211. this._target = target;
  31212. }
  31213. PlayAnimationAction.prototype._prepare = function () {
  31214. };
  31215. PlayAnimationAction.prototype.execute = function () {
  31216. var scene = this._actionManager.getScene();
  31217. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  31218. };
  31219. PlayAnimationAction.prototype.serialize = function (parent) {
  31220. return _super.prototype._serialize.call(this, {
  31221. name: "PlayAnimationAction",
  31222. properties: [
  31223. BABYLON.Action._GetTargetProperty(this._target),
  31224. { name: "from", value: String(this.from) },
  31225. { name: "to", value: String(this.to) },
  31226. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  31227. ]
  31228. }, parent);
  31229. };
  31230. return PlayAnimationAction;
  31231. })(BABYLON.Action);
  31232. BABYLON.PlayAnimationAction = PlayAnimationAction;
  31233. var StopAnimationAction = (function (_super) {
  31234. __extends(StopAnimationAction, _super);
  31235. function StopAnimationAction(triggerOptions, target, condition) {
  31236. _super.call(this, triggerOptions, condition);
  31237. this._target = target;
  31238. }
  31239. StopAnimationAction.prototype._prepare = function () {
  31240. };
  31241. StopAnimationAction.prototype.execute = function () {
  31242. var scene = this._actionManager.getScene();
  31243. scene.stopAnimation(this._target);
  31244. };
  31245. StopAnimationAction.prototype.serialize = function (parent) {
  31246. return _super.prototype._serialize.call(this, {
  31247. name: "StopAnimationAction",
  31248. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  31249. }, parent);
  31250. };
  31251. return StopAnimationAction;
  31252. })(BABYLON.Action);
  31253. BABYLON.StopAnimationAction = StopAnimationAction;
  31254. var DoNothingAction = (function (_super) {
  31255. __extends(DoNothingAction, _super);
  31256. function DoNothingAction(triggerOptions, condition) {
  31257. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  31258. _super.call(this, triggerOptions, condition);
  31259. }
  31260. DoNothingAction.prototype.execute = function () {
  31261. };
  31262. DoNothingAction.prototype.serialize = function (parent) {
  31263. return _super.prototype._serialize.call(this, {
  31264. name: "DoNothingAction",
  31265. properties: []
  31266. }, parent);
  31267. };
  31268. return DoNothingAction;
  31269. })(BABYLON.Action);
  31270. BABYLON.DoNothingAction = DoNothingAction;
  31271. var CombineAction = (function (_super) {
  31272. __extends(CombineAction, _super);
  31273. function CombineAction(triggerOptions, children, condition) {
  31274. _super.call(this, triggerOptions, condition);
  31275. this.children = children;
  31276. }
  31277. CombineAction.prototype._prepare = function () {
  31278. for (var index = 0; index < this.children.length; index++) {
  31279. this.children[index]._actionManager = this._actionManager;
  31280. this.children[index]._prepare();
  31281. }
  31282. };
  31283. CombineAction.prototype.execute = function (evt) {
  31284. for (var index = 0; index < this.children.length; index++) {
  31285. this.children[index].execute(evt);
  31286. }
  31287. };
  31288. CombineAction.prototype.serialize = function (parent) {
  31289. var serializationObject = _super.prototype._serialize.call(this, {
  31290. name: "CombineAction",
  31291. properties: [],
  31292. combine: []
  31293. }, parent);
  31294. for (var i = 0; i < this.children.length; i++) {
  31295. serializationObject.combine.push(this.children[i].serialize(null));
  31296. }
  31297. return serializationObject;
  31298. };
  31299. return CombineAction;
  31300. })(BABYLON.Action);
  31301. BABYLON.CombineAction = CombineAction;
  31302. var ExecuteCodeAction = (function (_super) {
  31303. __extends(ExecuteCodeAction, _super);
  31304. function ExecuteCodeAction(triggerOptions, func, condition) {
  31305. _super.call(this, triggerOptions, condition);
  31306. this.func = func;
  31307. }
  31308. ExecuteCodeAction.prototype.execute = function (evt) {
  31309. this.func(evt);
  31310. };
  31311. return ExecuteCodeAction;
  31312. })(BABYLON.Action);
  31313. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  31314. var SetParentAction = (function (_super) {
  31315. __extends(SetParentAction, _super);
  31316. function SetParentAction(triggerOptions, target, parent, condition) {
  31317. _super.call(this, triggerOptions, condition);
  31318. this._target = target;
  31319. this._parent = parent;
  31320. }
  31321. SetParentAction.prototype._prepare = function () {
  31322. };
  31323. SetParentAction.prototype.execute = function () {
  31324. if (this._target.parent === this._parent) {
  31325. return;
  31326. }
  31327. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  31328. invertParentWorldMatrix.invert();
  31329. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  31330. this._target.parent = this._parent;
  31331. };
  31332. SetParentAction.prototype.serialize = function (parent) {
  31333. return _super.prototype._serialize.call(this, {
  31334. name: "SetParentAction",
  31335. properties: [
  31336. BABYLON.Action._GetTargetProperty(this._target),
  31337. BABYLON.Action._GetTargetProperty(this._parent),
  31338. ]
  31339. }, parent);
  31340. };
  31341. return SetParentAction;
  31342. })(BABYLON.Action);
  31343. BABYLON.SetParentAction = SetParentAction;
  31344. var PlaySoundAction = (function (_super) {
  31345. __extends(PlaySoundAction, _super);
  31346. function PlaySoundAction(triggerOptions, sound, condition) {
  31347. _super.call(this, triggerOptions, condition);
  31348. this._sound = sound;
  31349. }
  31350. PlaySoundAction.prototype._prepare = function () {
  31351. };
  31352. PlaySoundAction.prototype.execute = function () {
  31353. if (this._sound !== undefined)
  31354. this._sound.play();
  31355. };
  31356. PlaySoundAction.prototype.serialize = function (parent) {
  31357. return _super.prototype._serialize.call(this, {
  31358. name: "PlaySoundAction",
  31359. properties: [{ name: "sound", value: this._sound.name }]
  31360. }, parent);
  31361. };
  31362. return PlaySoundAction;
  31363. })(BABYLON.Action);
  31364. BABYLON.PlaySoundAction = PlaySoundAction;
  31365. var StopSoundAction = (function (_super) {
  31366. __extends(StopSoundAction, _super);
  31367. function StopSoundAction(triggerOptions, sound, condition) {
  31368. _super.call(this, triggerOptions, condition);
  31369. this._sound = sound;
  31370. }
  31371. StopSoundAction.prototype._prepare = function () {
  31372. };
  31373. StopSoundAction.prototype.execute = function () {
  31374. if (this._sound !== undefined)
  31375. this._sound.stop();
  31376. };
  31377. StopSoundAction.prototype.serialize = function (parent) {
  31378. return _super.prototype._serialize.call(this, {
  31379. name: "StopSoundAction",
  31380. properties: [{ name: "sound", value: this._sound.name }]
  31381. }, parent);
  31382. };
  31383. return StopSoundAction;
  31384. })(BABYLON.Action);
  31385. BABYLON.StopSoundAction = StopSoundAction;
  31386. })(BABYLON || (BABYLON = {}));
  31387. var BABYLON;
  31388. (function (BABYLON) {
  31389. var Geometry = (function () {
  31390. function Geometry(id, scene, vertexData, updatable, mesh) {
  31391. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31392. this._totalVertices = 0;
  31393. this._isDisposed = false;
  31394. this.id = id;
  31395. this._engine = scene.getEngine();
  31396. this._meshes = [];
  31397. this._scene = scene;
  31398. //Init vertex buffer cache
  31399. this._vertexBuffers = {};
  31400. this._indices = [];
  31401. // vertexData
  31402. if (vertexData) {
  31403. this.setAllVerticesData(vertexData, updatable);
  31404. }
  31405. else {
  31406. this._totalVertices = 0;
  31407. this._indices = [];
  31408. }
  31409. // applyToMesh
  31410. if (mesh) {
  31411. if (mesh instanceof BABYLON.LinesMesh) {
  31412. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31413. this.updateExtend();
  31414. }
  31415. this.applyToMesh(mesh);
  31416. mesh.computeWorldMatrix(true);
  31417. }
  31418. }
  31419. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31420. /**
  31421. * 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
  31422. * @returns The Bias Vector
  31423. */
  31424. get: function () {
  31425. return this._boundingBias;
  31426. },
  31427. set: function (value) {
  31428. if (this._boundingBias && this._boundingBias.equals(value)) {
  31429. return;
  31430. }
  31431. this._boundingBias = value.clone();
  31432. this.updateBoundingInfo(true, null);
  31433. },
  31434. enumerable: true,
  31435. configurable: true
  31436. });
  31437. Object.defineProperty(Geometry.prototype, "extend", {
  31438. get: function () {
  31439. return this._extend;
  31440. },
  31441. enumerable: true,
  31442. configurable: true
  31443. });
  31444. Geometry.prototype.getScene = function () {
  31445. return this._scene;
  31446. };
  31447. Geometry.prototype.getEngine = function () {
  31448. return this._engine;
  31449. };
  31450. Geometry.prototype.isReady = function () {
  31451. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31452. };
  31453. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31454. vertexData.applyToGeometry(this, updatable);
  31455. this.notifyUpdate();
  31456. };
  31457. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31458. if (this._vertexBuffers[kind]) {
  31459. this._vertexBuffers[kind].dispose();
  31460. }
  31461. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31462. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31463. stride = this._vertexBuffers[kind].getStrideSize();
  31464. this._totalVertices = data.length / stride;
  31465. this.updateExtend(data);
  31466. var meshes = this._meshes;
  31467. var numOfMeshes = meshes.length;
  31468. for (var index = 0; index < numOfMeshes; index++) {
  31469. var mesh = meshes[index];
  31470. mesh._resetPointsArrayCache();
  31471. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31472. mesh._createGlobalSubMesh();
  31473. mesh.computeWorldMatrix(true);
  31474. }
  31475. }
  31476. this.notifyUpdate(kind);
  31477. };
  31478. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31479. var vertexBuffer = this.getVertexBuffer(kind);
  31480. if (!vertexBuffer) {
  31481. return;
  31482. }
  31483. vertexBuffer.updateDirectly(data, offset);
  31484. this.notifyUpdate(kind);
  31485. };
  31486. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31487. var vertexBuffer = this.getVertexBuffer(kind);
  31488. if (!vertexBuffer) {
  31489. return;
  31490. }
  31491. vertexBuffer.update(data);
  31492. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31493. var stride = vertexBuffer.getStrideSize();
  31494. this._totalVertices = data.length / stride;
  31495. this.updateBoundingInfo(updateExtends, data);
  31496. }
  31497. this.notifyUpdate(kind);
  31498. };
  31499. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31500. if (updateExtends) {
  31501. this.updateExtend(data);
  31502. }
  31503. var meshes = this._meshes;
  31504. var numOfMeshes = meshes.length;
  31505. for (var index = 0; index < numOfMeshes; index++) {
  31506. var mesh = meshes[index];
  31507. mesh._resetPointsArrayCache();
  31508. if (updateExtends) {
  31509. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31510. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31511. var subMesh = mesh.subMeshes[subIndex];
  31512. subMesh.refreshBoundingInfo();
  31513. }
  31514. }
  31515. }
  31516. };
  31517. Geometry.prototype.getTotalVertices = function () {
  31518. if (!this.isReady()) {
  31519. return 0;
  31520. }
  31521. return this._totalVertices;
  31522. };
  31523. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  31524. var vertexBuffer = this.getVertexBuffer(kind);
  31525. if (!vertexBuffer) {
  31526. return null;
  31527. }
  31528. var orig = vertexBuffer.getData();
  31529. if (!copyWhenShared || this._meshes.length === 1) {
  31530. return orig;
  31531. }
  31532. else {
  31533. var len = orig.length;
  31534. var copy = [];
  31535. for (var i = 0; i < len; i++) {
  31536. copy.push(orig[i]);
  31537. }
  31538. return copy;
  31539. }
  31540. };
  31541. Geometry.prototype.getVertexBuffer = function (kind) {
  31542. if (!this.isReady()) {
  31543. return null;
  31544. }
  31545. return this._vertexBuffers[kind];
  31546. };
  31547. Geometry.prototype.getVertexBuffers = function () {
  31548. if (!this.isReady()) {
  31549. return null;
  31550. }
  31551. return this._vertexBuffers;
  31552. };
  31553. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31554. if (!this._vertexBuffers) {
  31555. if (this._delayInfo) {
  31556. return this._delayInfo.indexOf(kind) !== -1;
  31557. }
  31558. return false;
  31559. }
  31560. return this._vertexBuffers[kind] !== undefined;
  31561. };
  31562. Geometry.prototype.getVerticesDataKinds = function () {
  31563. var result = [];
  31564. var kind;
  31565. if (!this._vertexBuffers && this._delayInfo) {
  31566. for (kind in this._delayInfo) {
  31567. result.push(kind);
  31568. }
  31569. }
  31570. else {
  31571. for (kind in this._vertexBuffers) {
  31572. result.push(kind);
  31573. }
  31574. }
  31575. return result;
  31576. };
  31577. Geometry.prototype.setIndices = function (indices, totalVertices) {
  31578. if (this._indexBuffer) {
  31579. this._engine._releaseBuffer(this._indexBuffer);
  31580. }
  31581. this._indices = indices;
  31582. if (this._meshes.length !== 0 && this._indices) {
  31583. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31584. }
  31585. if (totalVertices !== undefined) {
  31586. this._totalVertices = totalVertices;
  31587. }
  31588. var meshes = this._meshes;
  31589. var numOfMeshes = meshes.length;
  31590. for (var index = 0; index < numOfMeshes; index++) {
  31591. meshes[index]._createGlobalSubMesh();
  31592. }
  31593. this.notifyUpdate();
  31594. };
  31595. Geometry.prototype.getTotalIndices = function () {
  31596. if (!this.isReady()) {
  31597. return 0;
  31598. }
  31599. return this._indices.length;
  31600. };
  31601. Geometry.prototype.getIndices = function (copyWhenShared) {
  31602. if (!this.isReady()) {
  31603. return null;
  31604. }
  31605. var orig = this._indices;
  31606. if (!copyWhenShared || this._meshes.length === 1) {
  31607. return orig;
  31608. }
  31609. else {
  31610. var len = orig.length;
  31611. var copy = [];
  31612. for (var i = 0; i < len; i++) {
  31613. copy.push(orig[i]);
  31614. }
  31615. return copy;
  31616. }
  31617. };
  31618. Geometry.prototype.getIndexBuffer = function () {
  31619. if (!this.isReady()) {
  31620. return null;
  31621. }
  31622. return this._indexBuffer;
  31623. };
  31624. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31625. var meshes = this._meshes;
  31626. var index = meshes.indexOf(mesh);
  31627. if (index === -1) {
  31628. return;
  31629. }
  31630. for (var kind in this._vertexBuffers) {
  31631. this._vertexBuffers[kind].dispose();
  31632. }
  31633. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  31634. this._indexBuffer = null;
  31635. }
  31636. meshes.splice(index, 1);
  31637. mesh._geometry = null;
  31638. if (meshes.length === 0 && shouldDispose) {
  31639. this.dispose();
  31640. }
  31641. };
  31642. Geometry.prototype.applyToMesh = function (mesh) {
  31643. if (mesh._geometry === this) {
  31644. return;
  31645. }
  31646. var previousGeometry = mesh._geometry;
  31647. if (previousGeometry) {
  31648. previousGeometry.releaseForMesh(mesh);
  31649. }
  31650. var meshes = this._meshes;
  31651. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31652. mesh._geometry = this;
  31653. this._scene.pushGeometry(this);
  31654. meshes.push(mesh);
  31655. if (this.isReady()) {
  31656. this._applyToMesh(mesh);
  31657. }
  31658. else {
  31659. mesh._boundingInfo = this._boundingInfo;
  31660. }
  31661. };
  31662. Geometry.prototype.updateExtend = function (data) {
  31663. if (data === void 0) { data = null; }
  31664. if (!data) {
  31665. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31666. }
  31667. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  31668. };
  31669. Geometry.prototype._applyToMesh = function (mesh) {
  31670. var numOfMeshes = this._meshes.length;
  31671. // vertexBuffers
  31672. for (var kind in this._vertexBuffers) {
  31673. if (numOfMeshes === 1) {
  31674. this._vertexBuffers[kind].create();
  31675. }
  31676. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31677. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31678. mesh._resetPointsArrayCache();
  31679. if (!this._extend) {
  31680. this.updateExtend(this._vertexBuffers[kind].getData());
  31681. }
  31682. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31683. mesh._createGlobalSubMesh();
  31684. //bounding info was just created again, world matrix should be applied again.
  31685. mesh._updateBoundingInfo();
  31686. }
  31687. }
  31688. // indexBuffer
  31689. if (numOfMeshes === 1 && this._indices) {
  31690. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31691. }
  31692. if (this._indexBuffer) {
  31693. this._indexBuffer.references = numOfMeshes;
  31694. }
  31695. };
  31696. Geometry.prototype.notifyUpdate = function (kind) {
  31697. if (this.onGeometryUpdated) {
  31698. this.onGeometryUpdated(this, kind);
  31699. }
  31700. };
  31701. Geometry.prototype.load = function (scene, onLoaded) {
  31702. var _this = this;
  31703. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31704. return;
  31705. }
  31706. if (this.isReady()) {
  31707. if (onLoaded) {
  31708. onLoaded();
  31709. }
  31710. return;
  31711. }
  31712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31713. scene._addPendingData(this);
  31714. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31715. _this._delayLoadingFunction(JSON.parse(data), _this);
  31716. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31717. _this._delayInfo = [];
  31718. scene._removePendingData(_this);
  31719. var meshes = _this._meshes;
  31720. var numOfMeshes = meshes.length;
  31721. for (var index = 0; index < numOfMeshes; index++) {
  31722. _this._applyToMesh(meshes[index]);
  31723. }
  31724. if (onLoaded) {
  31725. onLoaded();
  31726. }
  31727. }, function () { }, scene.database);
  31728. };
  31729. Geometry.prototype.isDisposed = function () {
  31730. return this._isDisposed;
  31731. };
  31732. Geometry.prototype.dispose = function () {
  31733. var meshes = this._meshes;
  31734. var numOfMeshes = meshes.length;
  31735. var index;
  31736. for (index = 0; index < numOfMeshes; index++) {
  31737. this.releaseForMesh(meshes[index]);
  31738. }
  31739. this._meshes = [];
  31740. for (var kind in this._vertexBuffers) {
  31741. this._vertexBuffers[kind].dispose();
  31742. }
  31743. this._vertexBuffers = [];
  31744. this._totalVertices = 0;
  31745. if (this._indexBuffer) {
  31746. this._engine._releaseBuffer(this._indexBuffer);
  31747. }
  31748. this._indexBuffer = null;
  31749. this._indices = [];
  31750. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31751. this.delayLoadingFile = null;
  31752. this._delayLoadingFunction = null;
  31753. this._delayInfo = [];
  31754. this._boundingInfo = null;
  31755. this._scene.removeGeometry(this);
  31756. this._isDisposed = true;
  31757. };
  31758. Geometry.prototype.copy = function (id) {
  31759. var vertexData = new BABYLON.VertexData();
  31760. vertexData.indices = [];
  31761. var indices = this.getIndices();
  31762. for (var index = 0; index < indices.length; index++) {
  31763. vertexData.indices.push(indices[index]);
  31764. }
  31765. var updatable = false;
  31766. var stopChecking = false;
  31767. var kind;
  31768. for (kind in this._vertexBuffers) {
  31769. // using slice() to make a copy of the array and not just reference it
  31770. var data = this.getVerticesData(kind);
  31771. if (data instanceof Float32Array) {
  31772. vertexData.set(new Float32Array(data), kind);
  31773. }
  31774. else {
  31775. vertexData.set(data.slice(0), kind);
  31776. }
  31777. if (!stopChecking) {
  31778. updatable = this.getVertexBuffer(kind).isUpdatable();
  31779. stopChecking = !updatable;
  31780. }
  31781. }
  31782. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31783. geometry.delayLoadState = this.delayLoadState;
  31784. geometry.delayLoadingFile = this.delayLoadingFile;
  31785. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31786. for (kind in this._delayInfo) {
  31787. geometry._delayInfo = geometry._delayInfo || [];
  31788. geometry._delayInfo.push(kind);
  31789. }
  31790. // Bounding info
  31791. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31792. return geometry;
  31793. };
  31794. Geometry.prototype.serialize = function () {
  31795. var serializationObject = {};
  31796. serializationObject.id = this.id;
  31797. if (BABYLON.Tags.HasTags(this)) {
  31798. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31799. }
  31800. return serializationObject;
  31801. };
  31802. Geometry.prototype.serializeVerticeData = function () {
  31803. var serializationObject = this.serialize();
  31804. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31805. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31806. }
  31807. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31808. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31809. }
  31810. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31811. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31812. }
  31813. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31814. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31815. }
  31816. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31817. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31818. }
  31819. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31820. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31821. }
  31822. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31823. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31824. }
  31825. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31826. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31827. }
  31828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31829. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31830. }
  31831. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31832. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31833. serializationObject.matricesIndices._isExpanded = true;
  31834. }
  31835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31836. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31837. }
  31838. serializationObject.indices = this.getIndices();
  31839. return serializationObject;
  31840. };
  31841. // Statics
  31842. Geometry.ExtractFromMesh = function (mesh, id) {
  31843. var geometry = mesh._geometry;
  31844. if (!geometry) {
  31845. return null;
  31846. }
  31847. return geometry.copy(id);
  31848. };
  31849. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31850. // be aware Math.random() could cause collisions
  31851. Geometry.RandomId = function () {
  31852. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31853. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31854. return v.toString(16);
  31855. });
  31856. };
  31857. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31858. var scene = mesh.getScene();
  31859. // Geometry
  31860. var geometryId = parsedGeometry.geometryId;
  31861. if (geometryId) {
  31862. var geometry = scene.getGeometryByID(geometryId);
  31863. if (geometry) {
  31864. geometry.applyToMesh(mesh);
  31865. }
  31866. }
  31867. else if (parsedGeometry instanceof ArrayBuffer) {
  31868. var binaryInfo = mesh._binaryInfo;
  31869. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31870. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31871. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31872. }
  31873. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31874. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31875. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31876. }
  31877. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31878. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31879. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31880. }
  31881. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31882. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31883. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31884. }
  31885. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31886. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31887. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31888. }
  31889. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31890. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31891. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31892. }
  31893. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31894. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31895. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31896. }
  31897. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31898. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31899. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31900. }
  31901. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31902. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31903. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31904. }
  31905. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31906. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31907. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31908. }
  31909. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31910. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31911. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31912. }
  31913. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31914. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31915. mesh.setIndices(indicesData);
  31916. }
  31917. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31918. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31919. mesh.subMeshes = [];
  31920. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31921. var materialIndex = subMeshesData[(i * 5) + 0];
  31922. var verticesStart = subMeshesData[(i * 5) + 1];
  31923. var verticesCount = subMeshesData[(i * 5) + 2];
  31924. var indexStart = subMeshesData[(i * 5) + 3];
  31925. var indexCount = subMeshesData[(i * 5) + 4];
  31926. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31927. }
  31928. }
  31929. }
  31930. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31931. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31932. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31933. if (parsedGeometry.uvs) {
  31934. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31935. }
  31936. if (parsedGeometry.uvs2) {
  31937. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31938. }
  31939. if (parsedGeometry.uvs3) {
  31940. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31941. }
  31942. if (parsedGeometry.uvs4) {
  31943. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31944. }
  31945. if (parsedGeometry.uvs5) {
  31946. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31947. }
  31948. if (parsedGeometry.uvs6) {
  31949. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31950. }
  31951. if (parsedGeometry.colors) {
  31952. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31953. }
  31954. if (parsedGeometry.matricesIndices) {
  31955. if (!parsedGeometry.matricesIndices._isExpanded) {
  31956. var floatIndices = [];
  31957. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31958. var matricesIndex = parsedGeometry.matricesIndices[i];
  31959. floatIndices.push(matricesIndex & 0x000000FF);
  31960. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31961. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31962. floatIndices.push(matricesIndex >> 24);
  31963. }
  31964. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31965. }
  31966. else {
  31967. delete parsedGeometry.matricesIndices._isExpanded;
  31968. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31969. }
  31970. }
  31971. if (parsedGeometry.matricesIndicesExtra) {
  31972. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31973. var floatIndices = [];
  31974. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31975. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31976. floatIndices.push(matricesIndex & 0x000000FF);
  31977. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31978. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31979. floatIndices.push(matricesIndex >> 24);
  31980. }
  31981. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  31982. }
  31983. else {
  31984. delete parsedGeometry.matricesIndices._isExpanded;
  31985. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  31986. }
  31987. }
  31988. if (parsedGeometry.matricesWeights) {
  31989. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  31990. }
  31991. if (parsedGeometry.matricesWeightsExtra) {
  31992. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  31993. }
  31994. mesh.setIndices(parsedGeometry.indices);
  31995. }
  31996. // SubMeshes
  31997. if (parsedGeometry.subMeshes) {
  31998. mesh.subMeshes = [];
  31999. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32000. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32001. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32002. }
  32003. }
  32004. // Flat shading
  32005. if (mesh._shouldGenerateFlatShading) {
  32006. mesh.convertToFlatShadedMesh();
  32007. delete mesh._shouldGenerateFlatShading;
  32008. }
  32009. // Update
  32010. mesh.computeWorldMatrix(true);
  32011. // Octree
  32012. if (scene['_selectionOctree']) {
  32013. scene['_selectionOctree'].addMesh(mesh);
  32014. }
  32015. };
  32016. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32017. if (scene.getGeometryByID(parsedVertexData.id)) {
  32018. return null; // null since geometry could be something else than a box...
  32019. }
  32020. var geometry = new Geometry(parsedVertexData.id, scene);
  32021. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32022. if (parsedVertexData.delayLoadingFile) {
  32023. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32024. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32025. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32026. geometry._delayInfo = [];
  32027. if (parsedVertexData.hasUVs) {
  32028. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32029. }
  32030. if (parsedVertexData.hasUVs2) {
  32031. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32032. }
  32033. if (parsedVertexData.hasUVs3) {
  32034. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32035. }
  32036. if (parsedVertexData.hasUVs4) {
  32037. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32038. }
  32039. if (parsedVertexData.hasUVs5) {
  32040. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32041. }
  32042. if (parsedVertexData.hasUVs6) {
  32043. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32044. }
  32045. if (parsedVertexData.hasColors) {
  32046. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32047. }
  32048. if (parsedVertexData.hasMatricesIndices) {
  32049. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32050. }
  32051. if (parsedVertexData.hasMatricesWeights) {
  32052. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32053. }
  32054. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32055. }
  32056. else {
  32057. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32058. }
  32059. scene.pushGeometry(geometry, true);
  32060. return geometry;
  32061. };
  32062. return Geometry;
  32063. })();
  32064. BABYLON.Geometry = Geometry;
  32065. /////// Primitives //////////////////////////////////////////////
  32066. var Geometry;
  32067. (function (Geometry) {
  32068. var Primitives;
  32069. (function (Primitives) {
  32070. /// Abstract class
  32071. var _Primitive = (function (_super) {
  32072. __extends(_Primitive, _super);
  32073. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  32074. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  32075. this._canBeRegenerated = _canBeRegenerated;
  32076. this._beingRegenerated = true;
  32077. this.regenerate();
  32078. this._beingRegenerated = false;
  32079. }
  32080. _Primitive.prototype.canBeRegenerated = function () {
  32081. return this._canBeRegenerated;
  32082. };
  32083. _Primitive.prototype.regenerate = function () {
  32084. if (!this._canBeRegenerated) {
  32085. return;
  32086. }
  32087. this._beingRegenerated = true;
  32088. this.setAllVerticesData(this._regenerateVertexData(), false);
  32089. this._beingRegenerated = false;
  32090. };
  32091. _Primitive.prototype.asNewGeometry = function (id) {
  32092. return _super.prototype.copy.call(this, id);
  32093. };
  32094. // overrides
  32095. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  32096. if (!this._beingRegenerated) {
  32097. return;
  32098. }
  32099. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32100. };
  32101. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  32102. if (!this._beingRegenerated) {
  32103. return;
  32104. }
  32105. _super.prototype.setVerticesData.call(this, kind, data, false);
  32106. };
  32107. // to override
  32108. // protected
  32109. _Primitive.prototype._regenerateVertexData = function () {
  32110. throw new Error("Abstract method");
  32111. };
  32112. _Primitive.prototype.copy = function (id) {
  32113. throw new Error("Must be overriden in sub-classes.");
  32114. };
  32115. _Primitive.prototype.serialize = function () {
  32116. var serializationObject = _super.prototype.serialize.call(this);
  32117. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32118. return serializationObject;
  32119. };
  32120. return _Primitive;
  32121. })(Geometry);
  32122. Primitives._Primitive = _Primitive;
  32123. var Ribbon = (function (_super) {
  32124. __extends(Ribbon, _super);
  32125. // Members
  32126. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32127. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32128. _super.call(this, id, scene, canBeRegenerated, mesh);
  32129. this.pathArray = pathArray;
  32130. this.closeArray = closeArray;
  32131. this.closePath = closePath;
  32132. this.offset = offset;
  32133. this.side = side;
  32134. }
  32135. Ribbon.prototype._regenerateVertexData = function () {
  32136. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32137. };
  32138. Ribbon.prototype.copy = function (id) {
  32139. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  32140. };
  32141. return Ribbon;
  32142. })(_Primitive);
  32143. Primitives.Ribbon = Ribbon;
  32144. var Box = (function (_super) {
  32145. __extends(Box, _super);
  32146. // Members
  32147. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32148. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32149. _super.call(this, id, scene, canBeRegenerated, mesh);
  32150. this.size = size;
  32151. this.side = side;
  32152. }
  32153. Box.prototype._regenerateVertexData = function () {
  32154. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32155. };
  32156. Box.prototype.copy = function (id) {
  32157. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32158. };
  32159. Box.prototype.serialize = function () {
  32160. var serializationObject = _super.prototype.serialize.call(this);
  32161. serializationObject.size = this.size;
  32162. return serializationObject;
  32163. };
  32164. Box.Parse = function (parsedBox, scene) {
  32165. if (scene.getGeometryByID(parsedBox.id)) {
  32166. return null; // null since geometry could be something else than a box...
  32167. }
  32168. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32169. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32170. scene.pushGeometry(box, true);
  32171. return box;
  32172. };
  32173. return Box;
  32174. })(_Primitive);
  32175. Primitives.Box = Box;
  32176. var Sphere = (function (_super) {
  32177. __extends(Sphere, _super);
  32178. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32179. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32180. _super.call(this, id, scene, canBeRegenerated, mesh);
  32181. this.segments = segments;
  32182. this.diameter = diameter;
  32183. this.side = side;
  32184. }
  32185. Sphere.prototype._regenerateVertexData = function () {
  32186. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32187. };
  32188. Sphere.prototype.copy = function (id) {
  32189. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32190. };
  32191. Sphere.prototype.serialize = function () {
  32192. var serializationObject = _super.prototype.serialize.call(this);
  32193. serializationObject.segments = this.segments;
  32194. serializationObject.diameter = this.diameter;
  32195. return serializationObject;
  32196. };
  32197. Sphere.Parse = function (parsedSphere, scene) {
  32198. if (scene.getGeometryByID(parsedSphere.id)) {
  32199. return null; // null since geometry could be something else than a sphere...
  32200. }
  32201. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32202. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32203. scene.pushGeometry(sphere, true);
  32204. return sphere;
  32205. };
  32206. return Sphere;
  32207. })(_Primitive);
  32208. Primitives.Sphere = Sphere;
  32209. var Disc = (function (_super) {
  32210. __extends(Disc, _super);
  32211. // Members
  32212. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32213. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32214. _super.call(this, id, scene, canBeRegenerated, mesh);
  32215. this.radius = radius;
  32216. this.tessellation = tessellation;
  32217. this.side = side;
  32218. }
  32219. Disc.prototype._regenerateVertexData = function () {
  32220. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32221. };
  32222. Disc.prototype.copy = function (id) {
  32223. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32224. };
  32225. return Disc;
  32226. })(_Primitive);
  32227. Primitives.Disc = Disc;
  32228. var Cylinder = (function (_super) {
  32229. __extends(Cylinder, _super);
  32230. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32231. if (subdivisions === void 0) { subdivisions = 1; }
  32232. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32233. _super.call(this, id, scene, canBeRegenerated, mesh);
  32234. this.height = height;
  32235. this.diameterTop = diameterTop;
  32236. this.diameterBottom = diameterBottom;
  32237. this.tessellation = tessellation;
  32238. this.subdivisions = subdivisions;
  32239. this.side = side;
  32240. }
  32241. Cylinder.prototype._regenerateVertexData = function () {
  32242. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32243. };
  32244. Cylinder.prototype.copy = function (id) {
  32245. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32246. };
  32247. Cylinder.prototype.serialize = function () {
  32248. var serializationObject = _super.prototype.serialize.call(this);
  32249. serializationObject.height = this.height;
  32250. serializationObject.diameterTop = this.diameterTop;
  32251. serializationObject.diameterBottom = this.diameterBottom;
  32252. serializationObject.tessellation = this.tessellation;
  32253. return serializationObject;
  32254. };
  32255. Cylinder.Parse = function (parsedCylinder, scene) {
  32256. if (scene.getGeometryByID(parsedCylinder.id)) {
  32257. return null; // null since geometry could be something else than a cylinder...
  32258. }
  32259. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32260. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32261. scene.pushGeometry(cylinder, true);
  32262. return cylinder;
  32263. };
  32264. return Cylinder;
  32265. })(_Primitive);
  32266. Primitives.Cylinder = Cylinder;
  32267. var Torus = (function (_super) {
  32268. __extends(Torus, _super);
  32269. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32270. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32271. _super.call(this, id, scene, canBeRegenerated, mesh);
  32272. this.diameter = diameter;
  32273. this.thickness = thickness;
  32274. this.tessellation = tessellation;
  32275. this.side = side;
  32276. }
  32277. Torus.prototype._regenerateVertexData = function () {
  32278. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32279. };
  32280. Torus.prototype.copy = function (id) {
  32281. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32282. };
  32283. Torus.prototype.serialize = function () {
  32284. var serializationObject = _super.prototype.serialize.call(this);
  32285. serializationObject.diameter = this.diameter;
  32286. serializationObject.thickness = this.thickness;
  32287. serializationObject.tessellation = this.tessellation;
  32288. return serializationObject;
  32289. };
  32290. Torus.Parse = function (parsedTorus, scene) {
  32291. if (scene.getGeometryByID(parsedTorus.id)) {
  32292. return null; // null since geometry could be something else than a torus...
  32293. }
  32294. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32295. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32296. scene.pushGeometry(torus, true);
  32297. return torus;
  32298. };
  32299. return Torus;
  32300. })(_Primitive);
  32301. Primitives.Torus = Torus;
  32302. var Ground = (function (_super) {
  32303. __extends(Ground, _super);
  32304. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32305. _super.call(this, id, scene, canBeRegenerated, mesh);
  32306. this.width = width;
  32307. this.height = height;
  32308. this.subdivisions = subdivisions;
  32309. }
  32310. Ground.prototype._regenerateVertexData = function () {
  32311. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32312. };
  32313. Ground.prototype.copy = function (id) {
  32314. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32315. };
  32316. Ground.prototype.serialize = function () {
  32317. var serializationObject = _super.prototype.serialize.call(this);
  32318. serializationObject.width = this.width;
  32319. serializationObject.height = this.height;
  32320. serializationObject.subdivisions = this.subdivisions;
  32321. return serializationObject;
  32322. };
  32323. Ground.Parse = function (parsedGround, scene) {
  32324. if (scene.getGeometryByID(parsedGround.id)) {
  32325. return null; // null since geometry could be something else than a ground...
  32326. }
  32327. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32328. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32329. scene.pushGeometry(ground, true);
  32330. return ground;
  32331. };
  32332. return Ground;
  32333. })(_Primitive);
  32334. Primitives.Ground = Ground;
  32335. var TiledGround = (function (_super) {
  32336. __extends(TiledGround, _super);
  32337. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32338. _super.call(this, id, scene, canBeRegenerated, mesh);
  32339. this.xmin = xmin;
  32340. this.zmin = zmin;
  32341. this.xmax = xmax;
  32342. this.zmax = zmax;
  32343. this.subdivisions = subdivisions;
  32344. this.precision = precision;
  32345. }
  32346. TiledGround.prototype._regenerateVertexData = function () {
  32347. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32348. };
  32349. TiledGround.prototype.copy = function (id) {
  32350. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32351. };
  32352. return TiledGround;
  32353. })(_Primitive);
  32354. Primitives.TiledGround = TiledGround;
  32355. var Plane = (function (_super) {
  32356. __extends(Plane, _super);
  32357. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32358. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32359. _super.call(this, id, scene, canBeRegenerated, mesh);
  32360. this.size = size;
  32361. this.side = side;
  32362. }
  32363. Plane.prototype._regenerateVertexData = function () {
  32364. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32365. };
  32366. Plane.prototype.copy = function (id) {
  32367. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32368. };
  32369. Plane.prototype.serialize = function () {
  32370. var serializationObject = _super.prototype.serialize.call(this);
  32371. serializationObject.size = this.size;
  32372. return serializationObject;
  32373. };
  32374. Plane.Parse = function (parsedPlane, scene) {
  32375. if (scene.getGeometryByID(parsedPlane.id)) {
  32376. return null; // null since geometry could be something else than a ground...
  32377. }
  32378. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32379. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32380. scene.pushGeometry(plane, true);
  32381. return plane;
  32382. };
  32383. return Plane;
  32384. })(_Primitive);
  32385. Primitives.Plane = Plane;
  32386. var TorusKnot = (function (_super) {
  32387. __extends(TorusKnot, _super);
  32388. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32389. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32390. _super.call(this, id, scene, canBeRegenerated, mesh);
  32391. this.radius = radius;
  32392. this.tube = tube;
  32393. this.radialSegments = radialSegments;
  32394. this.tubularSegments = tubularSegments;
  32395. this.p = p;
  32396. this.q = q;
  32397. this.side = side;
  32398. }
  32399. TorusKnot.prototype._regenerateVertexData = function () {
  32400. 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 });
  32401. };
  32402. TorusKnot.prototype.copy = function (id) {
  32403. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32404. };
  32405. TorusKnot.prototype.serialize = function () {
  32406. var serializationObject = _super.prototype.serialize.call(this);
  32407. serializationObject.radius = this.radius;
  32408. serializationObject.tube = this.tube;
  32409. serializationObject.radialSegments = this.radialSegments;
  32410. serializationObject.tubularSegments = this.tubularSegments;
  32411. serializationObject.p = this.p;
  32412. serializationObject.q = this.q;
  32413. return serializationObject;
  32414. };
  32415. ;
  32416. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32417. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32418. return null; // null since geometry could be something else than a ground...
  32419. }
  32420. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32421. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32422. scene.pushGeometry(torusKnot, true);
  32423. return torusKnot;
  32424. };
  32425. return TorusKnot;
  32426. })(_Primitive);
  32427. Primitives.TorusKnot = TorusKnot;
  32428. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32429. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32430. })(BABYLON || (BABYLON = {}));
  32431. var BABYLON;
  32432. (function (BABYLON) {
  32433. var GroundMesh = (function (_super) {
  32434. __extends(GroundMesh, _super);
  32435. function GroundMesh(name, scene) {
  32436. _super.call(this, name, scene);
  32437. this.generateOctree = false;
  32438. this._worldInverse = new BABYLON.Matrix();
  32439. }
  32440. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  32441. get: function () {
  32442. return this._subdivisions;
  32443. },
  32444. enumerable: true,
  32445. configurable: true
  32446. });
  32447. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  32448. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  32449. this._subdivisions = chunksCount;
  32450. this.subdivide(this._subdivisions);
  32451. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  32452. };
  32453. /**
  32454. * Returns a height (y) value in the Worl system :
  32455. * the ground altitude at the coordinates (x, z) expressed in the World system.
  32456. * Returns the ground y position if (x, z) are outside the ground surface.
  32457. * Not pertinent if the ground is rotated.
  32458. */
  32459. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  32460. // express x and y in the ground local system
  32461. x -= this.position.x;
  32462. z -= this.position.z;
  32463. x /= this.scaling.x;
  32464. z /= this.scaling.z;
  32465. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32466. return this.position.y;
  32467. }
  32468. if (!this._heightQuads || this._heightQuads.length == 0) {
  32469. this._initHeightQuads();
  32470. this._computeHeightQuads();
  32471. }
  32472. var facet = this._getFacetAt(x, z);
  32473. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  32474. // return y in the World system
  32475. return y * this.scaling.y + this.position.y;
  32476. };
  32477. /**
  32478. * Returns a normalized vector (Vector3) orthogonal to the ground
  32479. * at the ground coordinates (x, z) expressed in the World system.
  32480. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  32481. * Not pertinent if the ground is rotated.
  32482. */
  32483. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  32484. var normal = new BABYLON.Vector3(0, 1, 0);
  32485. this.getNormalAtCoordinatesToRef(x, z, normal);
  32486. return normal;
  32487. };
  32488. /**
  32489. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  32490. * at the ground coordinates (x, z) expressed in the World system.
  32491. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  32492. * Not pertinent if the ground is rotated.
  32493. */
  32494. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  32495. // express x and y in the ground local system
  32496. x -= this.position.x;
  32497. z -= this.position.z;
  32498. x /= this.scaling.x;
  32499. z /= this.scaling.z;
  32500. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  32501. return;
  32502. }
  32503. if (!this._heightQuads || this._heightQuads.length == 0) {
  32504. this._initHeightQuads();
  32505. this._computeHeightQuads();
  32506. }
  32507. var facet = this._getFacetAt(x, z);
  32508. ref.x = facet.x;
  32509. ref.y = facet.y;
  32510. ref.z = facet.z;
  32511. };
  32512. /**
  32513. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  32514. * if the ground has been updated.
  32515. * This can be used in the render loop
  32516. */
  32517. GroundMesh.prototype.updateCoordinateHeights = function () {
  32518. if (!this._heightQuads || this._heightQuads.length == 0) {
  32519. this._initHeightQuads();
  32520. }
  32521. this._computeHeightQuads();
  32522. };
  32523. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  32524. GroundMesh.prototype._getFacetAt = function (x, z) {
  32525. // retrieve col and row from x, z coordinates in the ground local system
  32526. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  32527. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  32528. var quad = this._heightQuads[row * this._subdivisions + col];
  32529. var facet;
  32530. if (z < quad.slope.x * x + quad.slope.y) {
  32531. facet = quad.facet1;
  32532. }
  32533. else {
  32534. facet = quad.facet2;
  32535. }
  32536. return facet;
  32537. };
  32538. // Creates and populates the heightMap array with "facet" elements :
  32539. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  32540. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32541. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32542. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32543. GroundMesh.prototype._initHeightQuads = function () {
  32544. this._heightQuads = new Array();
  32545. for (var row = 0; row < this._subdivisions; row++) {
  32546. for (var col = 0; col < this._subdivisions; col++) {
  32547. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  32548. this._heightQuads[row * this._subdivisions + col] = quad;
  32549. }
  32550. }
  32551. };
  32552. // Compute each quad element values and update the the heightMap array :
  32553. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32554. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32555. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32556. GroundMesh.prototype._computeHeightQuads = function () {
  32557. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32558. var v1 = BABYLON.Tmp.Vector3[0];
  32559. var v2 = BABYLON.Tmp.Vector3[1];
  32560. var v3 = BABYLON.Tmp.Vector3[2];
  32561. var v4 = BABYLON.Tmp.Vector3[3];
  32562. var v1v2 = BABYLON.Tmp.Vector3[4];
  32563. var v1v3 = BABYLON.Tmp.Vector3[5];
  32564. var v1v4 = BABYLON.Tmp.Vector3[6];
  32565. var norm1 = BABYLON.Tmp.Vector3[7];
  32566. var norm2 = BABYLON.Tmp.Vector3[8];
  32567. var i = 0;
  32568. var j = 0;
  32569. var k = 0;
  32570. var cd = 0; // 2D slope coefficient : z = cd * x + h
  32571. var h = 0;
  32572. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  32573. var d2 = 0;
  32574. for (var row = 0; row < this._subdivisions; row++) {
  32575. for (var col = 0; col < this._subdivisions; col++) {
  32576. i = col * 3;
  32577. j = row * (this._subdivisions + 1) * 3;
  32578. k = (row + 1) * (this._subdivisions + 1) * 3;
  32579. v1.x = positions[j + i];
  32580. v1.y = positions[j + i + 1];
  32581. v1.z = positions[j + i + 2];
  32582. v2.x = positions[j + i + 3];
  32583. v2.y = positions[j + i + 4];
  32584. v2.z = positions[j + i + 5];
  32585. v3.x = positions[k + i];
  32586. v3.y = positions[k + i + 1];
  32587. v3.z = positions[k + i + 2];
  32588. v4.x = positions[k + i + 3];
  32589. v4.y = positions[k + i + 4];
  32590. v4.z = positions[k + i + 5];
  32591. // 2D slope V1V4
  32592. cd = (v4.z - v1.z) / (v4.x - v1.x);
  32593. h = v1.z - cd * v1.x; // v1 belongs to the slope
  32594. // facet equations :
  32595. // we compute each facet normal vector
  32596. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  32597. // we compute the value d by applying the equation to v1 which belongs to the plane
  32598. // then we store the facet equation in a Vector4
  32599. v2.subtractToRef(v1, v1v2);
  32600. v3.subtractToRef(v1, v1v3);
  32601. v4.subtractToRef(v1, v1v4);
  32602. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  32603. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  32604. norm1.normalize();
  32605. norm2.normalize();
  32606. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  32607. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  32608. var quad = this._heightQuads[row * this._subdivisions + col];
  32609. quad.slope.copyFromFloats(cd, h);
  32610. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  32611. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  32612. }
  32613. }
  32614. };
  32615. return GroundMesh;
  32616. })(BABYLON.Mesh);
  32617. BABYLON.GroundMesh = GroundMesh;
  32618. })(BABYLON || (BABYLON = {}));
  32619. var BABYLON;
  32620. (function (BABYLON) {
  32621. var LinesMesh = (function (_super) {
  32622. __extends(LinesMesh, _super);
  32623. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  32624. if (parent === void 0) { parent = null; }
  32625. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  32626. this.color = new BABYLON.Color3(1, 1, 1);
  32627. this.alpha = 1;
  32628. if (source) {
  32629. this.color = source.color.clone();
  32630. this.alpha = source.alpha;
  32631. }
  32632. this._intersectionThreshold = 0.1;
  32633. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  32634. attributes: ["position"],
  32635. uniforms: ["worldViewProjection", "color"],
  32636. needAlphaBlending: true
  32637. });
  32638. }
  32639. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  32640. /**
  32641. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32642. * This margin is expressed in world space coordinates, so its value may vary.
  32643. * Default value is 0.1
  32644. * @returns the intersection Threshold value.
  32645. */
  32646. get: function () {
  32647. return this._intersectionThreshold;
  32648. },
  32649. /**
  32650. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32651. * This margin is expressed in world space coordinates, so its value may vary.
  32652. * @param value the new threshold to apply
  32653. */
  32654. set: function (value) {
  32655. if (this._intersectionThreshold === value) {
  32656. return;
  32657. }
  32658. this._intersectionThreshold = value;
  32659. if (this.geometry) {
  32660. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  32661. }
  32662. },
  32663. enumerable: true,
  32664. configurable: true
  32665. });
  32666. Object.defineProperty(LinesMesh.prototype, "material", {
  32667. get: function () {
  32668. return this._colorShader;
  32669. },
  32670. enumerable: true,
  32671. configurable: true
  32672. });
  32673. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32674. get: function () {
  32675. return false;
  32676. },
  32677. enumerable: true,
  32678. configurable: true
  32679. });
  32680. LinesMesh.prototype.createInstance = function (name) {
  32681. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  32682. return null;
  32683. };
  32684. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32685. var engine = this.getScene().getEngine();
  32686. var indexToBind = this._geometry.getIndexBuffer();
  32687. // VBOs
  32688. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32689. // Color
  32690. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32691. };
  32692. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32693. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32694. return;
  32695. }
  32696. var engine = this.getScene().getEngine();
  32697. // Draw order
  32698. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32699. };
  32700. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32701. this._colorShader.dispose();
  32702. _super.prototype.dispose.call(this, doNotRecurse);
  32703. };
  32704. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32705. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32706. };
  32707. return LinesMesh;
  32708. })(BABYLON.Mesh);
  32709. BABYLON.LinesMesh = LinesMesh;
  32710. })(BABYLON || (BABYLON = {}));
  32711. var BABYLON;
  32712. (function (BABYLON) {
  32713. var DebugLayer = (function () {
  32714. function DebugLayer(scene) {
  32715. var _this = this;
  32716. this._transformationMatrix = BABYLON.Matrix.Identity();
  32717. this._enabled = false;
  32718. this._labelsEnabled = false;
  32719. this._displayStatistics = true;
  32720. this._displayTree = false;
  32721. this._displayLogs = false;
  32722. this._skeletonViewers = new Array();
  32723. this._identityMatrix = BABYLON.Matrix.Identity();
  32724. this.axisRatio = 0.02;
  32725. this.accentColor = "orange";
  32726. this._scene = scene;
  32727. this._syncPositions = function () {
  32728. var engine = _this._scene.getEngine();
  32729. var canvasRect = engine.getRenderingCanvasClientRect();
  32730. if (_this._showUI) {
  32731. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32732. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32733. _this._statsDiv.style.width = "400px";
  32734. _this._statsDiv.style.height = "auto";
  32735. _this._statsSubsetDiv.style.maxHeight = "240px";
  32736. _this._optionsDiv.style.left = "0px";
  32737. _this._optionsDiv.style.top = "10px";
  32738. _this._optionsDiv.style.width = "200px";
  32739. _this._optionsDiv.style.height = "auto";
  32740. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32741. _this._logDiv.style.left = "0px";
  32742. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32743. _this._logDiv.style.width = "600px";
  32744. _this._logDiv.style.height = "160px";
  32745. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32746. _this._treeDiv.style.top = "10px";
  32747. _this._treeDiv.style.width = "300px";
  32748. _this._treeDiv.style.height = "auto";
  32749. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32750. }
  32751. _this._globalDiv.style.left = canvasRect.left + "px";
  32752. _this._globalDiv.style.top = canvasRect.top + "px";
  32753. _this._drawingCanvas.style.left = "0px";
  32754. _this._drawingCanvas.style.top = "0px";
  32755. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32756. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32757. var devicePixelRatio = window.devicePixelRatio || 1;
  32758. var context = _this._drawingContext;
  32759. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32760. context.mozBackingStorePixelRatio ||
  32761. context.msBackingStorePixelRatio ||
  32762. context.oBackingStorePixelRatio ||
  32763. context.backingStorePixelRatio || 1;
  32764. _this._ratio = devicePixelRatio / backingStoreRatio;
  32765. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32766. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32767. };
  32768. this._onCanvasClick = function (evt) {
  32769. _this._clickPosition = {
  32770. x: evt.clientX * _this._ratio,
  32771. y: evt.clientY * _this._ratio
  32772. };
  32773. };
  32774. this._syncUI = function () {
  32775. if (_this._showUI) {
  32776. if (_this._displayStatistics) {
  32777. _this._displayStats();
  32778. _this._statsDiv.style.display = "";
  32779. }
  32780. else {
  32781. _this._statsDiv.style.display = "none";
  32782. }
  32783. if (_this._displayLogs) {
  32784. _this._logDiv.style.display = "";
  32785. }
  32786. else {
  32787. _this._logDiv.style.display = "none";
  32788. }
  32789. if (_this._displayTree) {
  32790. _this._treeDiv.style.display = "";
  32791. if (_this._needToRefreshMeshesTree) {
  32792. _this._needToRefreshMeshesTree = false;
  32793. _this._refreshMeshesTreeContent();
  32794. }
  32795. }
  32796. else {
  32797. _this._treeDiv.style.display = "none";
  32798. }
  32799. }
  32800. };
  32801. this._syncData = function () {
  32802. if (_this._labelsEnabled || !_this._showUI) {
  32803. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32804. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32805. var engine = _this._scene.getEngine();
  32806. var viewport = _this._camera.viewport;
  32807. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32808. // Meshes
  32809. var meshes = _this._camera.getActiveMeshes();
  32810. var index;
  32811. var projectedPosition;
  32812. for (index = 0; index < meshes.length; index++) {
  32813. var mesh = meshes.data[index];
  32814. var position = mesh.getBoundingInfo().boundingSphere.center;
  32815. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32816. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32817. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32818. }
  32819. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32820. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32821. }
  32822. }
  32823. // Cameras
  32824. var cameras = _this._scene.cameras;
  32825. for (index = 0; index < cameras.length; index++) {
  32826. var camera = cameras[index];
  32827. if (camera === _this._camera) {
  32828. continue;
  32829. }
  32830. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32831. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32832. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32833. _this._camera.detachControl(engine.getRenderingCanvas());
  32834. _this._camera = camera;
  32835. _this._camera.attachControl(engine.getRenderingCanvas());
  32836. }, function () { return "purple"; });
  32837. }
  32838. }
  32839. // Lights
  32840. var lights = _this._scene.lights;
  32841. for (index = 0; index < lights.length; index++) {
  32842. var light = lights[index];
  32843. if (light.position) {
  32844. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32845. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32846. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32847. light.setEnabled(!light.isEnabled());
  32848. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32849. }
  32850. }
  32851. }
  32852. }
  32853. _this._clickPosition = undefined;
  32854. };
  32855. }
  32856. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32857. while (this._treeSubsetDiv.hasChildNodes()) {
  32858. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32859. }
  32860. // Add meshes
  32861. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32862. sortedArray.sort(function (a, b) {
  32863. if (a.name === b.name) {
  32864. return 0;
  32865. }
  32866. return (a.name > b.name) ? 1 : -1;
  32867. });
  32868. for (var index = 0; index < sortedArray.length; index++) {
  32869. var mesh = sortedArray[index];
  32870. if (!mesh.isEnabled()) {
  32871. continue;
  32872. }
  32873. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32874. m.isVisible = element.checked;
  32875. }, mesh);
  32876. }
  32877. };
  32878. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32879. this._drawingContext.beginPath();
  32880. this._drawingContext.moveTo(zero.x, zero.y);
  32881. this._drawingContext.lineTo(unit.x, unit.y);
  32882. this._drawingContext.strokeStyle = color;
  32883. this._drawingContext.lineWidth = 4;
  32884. this._drawingContext.stroke();
  32885. this._drawingContext.font = "normal 14px Segoe UI";
  32886. this._drawingContext.fillStyle = color;
  32887. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32888. };
  32889. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32890. var position = mesh.getBoundingInfo().boundingSphere.center;
  32891. var worldMatrix = mesh.getWorldMatrix();
  32892. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32893. var unit = (unprojectedVector.subtract(position)).length();
  32894. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32895. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32896. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32897. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32898. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32899. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32900. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32901. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32902. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32903. };
  32904. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32905. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32906. this._drawingContext.font = "normal 12px Segoe UI";
  32907. var textMetrics = this._drawingContext.measureText(text);
  32908. var centerX = projectedPosition.x - textMetrics.width / 2;
  32909. var centerY = projectedPosition.y;
  32910. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32911. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32912. onClick();
  32913. }
  32914. this._drawingContext.beginPath();
  32915. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32916. this._drawingContext.fillStyle = getFillStyle();
  32917. this._drawingContext.globalAlpha = 0.5;
  32918. this._drawingContext.fill();
  32919. this._drawingContext.globalAlpha = 1.0;
  32920. this._drawingContext.strokeStyle = '#FFFFFF';
  32921. this._drawingContext.lineWidth = 1;
  32922. this._drawingContext.stroke();
  32923. this._drawingContext.fillStyle = "#FFFFFF";
  32924. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32925. this._drawingContext.beginPath();
  32926. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32927. this._drawingContext.fill();
  32928. }
  32929. };
  32930. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32931. if (!this._clickPosition) {
  32932. return false;
  32933. }
  32934. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32935. return false;
  32936. }
  32937. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32938. return false;
  32939. }
  32940. return true;
  32941. };
  32942. DebugLayer.prototype.isVisible = function () {
  32943. return this._enabled;
  32944. };
  32945. DebugLayer.prototype.hide = function () {
  32946. if (!this._enabled) {
  32947. return;
  32948. }
  32949. this._enabled = false;
  32950. var engine = this._scene.getEngine();
  32951. this._scene.unregisterBeforeRender(this._syncData);
  32952. this._scene.unregisterAfterRender(this._syncUI);
  32953. this._rootElement.removeChild(this._globalDiv);
  32954. this._scene.forceShowBoundingBoxes = false;
  32955. this._scene.forceWireframe = false;
  32956. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32957. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32958. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32959. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32960. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32961. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32962. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32963. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32964. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32965. this._scene.shadowsEnabled = true;
  32966. this._scene.particlesEnabled = true;
  32967. this._scene.postProcessesEnabled = true;
  32968. this._scene.collisionsEnabled = true;
  32969. this._scene.lightsEnabled = true;
  32970. this._scene.texturesEnabled = true;
  32971. this._scene.lensFlaresEnabled = true;
  32972. this._scene.proceduralTexturesEnabled = true;
  32973. this._scene.renderTargetsEnabled = true;
  32974. this._scene.probesEnabled = true;
  32975. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  32976. this._clearSkeletonViewers();
  32977. };
  32978. DebugLayer.prototype._clearSkeletonViewers = function () {
  32979. for (var index = 0; index < this._skeletonViewers.length; index++) {
  32980. this._skeletonViewers[index].dispose();
  32981. }
  32982. this._skeletonViewers = [];
  32983. };
  32984. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  32985. if (showUI === void 0) { showUI = true; }
  32986. if (camera === void 0) { camera = null; }
  32987. if (rootElement === void 0) { rootElement = null; }
  32988. if (this._enabled) {
  32989. return;
  32990. }
  32991. this._enabled = true;
  32992. if (camera) {
  32993. this._camera = camera;
  32994. }
  32995. else {
  32996. this._camera = this._scene.activeCamera;
  32997. }
  32998. this._showUI = showUI;
  32999. var engine = this._scene.getEngine();
  33000. this._globalDiv = document.createElement("div");
  33001. this._rootElement = rootElement || document.body;
  33002. this._rootElement.appendChild(this._globalDiv);
  33003. this._generateDOMelements();
  33004. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  33005. this._syncPositions();
  33006. this._scene.registerBeforeRender(this._syncData);
  33007. this._scene.registerAfterRender(this._syncUI);
  33008. };
  33009. DebugLayer.prototype._clearLabels = function () {
  33010. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  33011. for (var index = 0; index < this._scene.meshes.length; index++) {
  33012. var mesh = this._scene.meshes[index];
  33013. mesh.renderOverlay = false;
  33014. }
  33015. };
  33016. DebugLayer.prototype._generateheader = function (root, text) {
  33017. var header = document.createElement("div");
  33018. header.innerHTML = text + "&nbsp;";
  33019. header.style.textAlign = "right";
  33020. header.style.width = "100%";
  33021. header.style.color = "white";
  33022. header.style.backgroundColor = "Black";
  33023. header.style.padding = "5px 5px 4px 0px";
  33024. header.style.marginLeft = "-5px";
  33025. header.style.fontWeight = "bold";
  33026. root.appendChild(header);
  33027. };
  33028. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  33029. var label = document.createElement("label");
  33030. label.style.display = "inline";
  33031. label.innerHTML = title;
  33032. label.style.color = color;
  33033. root.appendChild(label);
  33034. root.appendChild(document.createElement("br"));
  33035. };
  33036. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  33037. if (tag === void 0) { tag = null; }
  33038. var label = document.createElement("label");
  33039. label.style.display = "inline";
  33040. var boundingBoxesCheckbox = document.createElement("input");
  33041. boundingBoxesCheckbox.type = "checkbox";
  33042. boundingBoxesCheckbox.checked = initialState;
  33043. boundingBoxesCheckbox.style.display = "inline";
  33044. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  33045. boundingBoxesCheckbox.style.verticalAlign = "sub";
  33046. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  33047. task(evt.target, tag);
  33048. });
  33049. label.appendChild(boundingBoxesCheckbox);
  33050. var container = document.createElement("span");
  33051. var leftPart = document.createElement("span");
  33052. var rightPart = document.createElement("span");
  33053. rightPart.style.cssFloat = "right";
  33054. leftPart.innerHTML = leftTitle;
  33055. rightPart.innerHTML = rightTitle;
  33056. rightPart.style.fontSize = "12px";
  33057. rightPart.style.maxWidth = "200px";
  33058. container.appendChild(leftPart);
  33059. container.appendChild(rightPart);
  33060. label.appendChild(container);
  33061. root.appendChild(label);
  33062. root.appendChild(document.createElement("br"));
  33063. };
  33064. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  33065. if (tag === void 0) { tag = null; }
  33066. var label = document.createElement("label");
  33067. label.style.display = "inline";
  33068. var checkBox = document.createElement("input");
  33069. checkBox.type = "checkbox";
  33070. checkBox.checked = initialState;
  33071. checkBox.style.display = "inline";
  33072. checkBox.style.margin = "0px 5px 0px 0px";
  33073. checkBox.style.verticalAlign = "sub";
  33074. checkBox.addEventListener("change", function (evt) {
  33075. task(evt.target, tag);
  33076. });
  33077. label.appendChild(checkBox);
  33078. label.appendChild(document.createTextNode(title));
  33079. root.appendChild(label);
  33080. root.appendChild(document.createElement("br"));
  33081. };
  33082. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  33083. if (tag === void 0) { tag = null; }
  33084. var button = document.createElement("button");
  33085. button.innerHTML = title;
  33086. button.style.height = "24px";
  33087. button.style.width = "150px";
  33088. button.style.marginBottom = "5px";
  33089. button.style.color = "#444444";
  33090. button.style.border = "1px solid white";
  33091. button.className = "debugLayerButton";
  33092. button.addEventListener("click", function (evt) {
  33093. task(evt.target, tag);
  33094. });
  33095. root.appendChild(button);
  33096. root.appendChild(document.createElement("br"));
  33097. };
  33098. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  33099. if (tag === void 0) { tag = null; }
  33100. var label = document.createElement("label");
  33101. label.style.display = "inline";
  33102. var boundingBoxesRadio = document.createElement("input");
  33103. boundingBoxesRadio.type = "radio";
  33104. boundingBoxesRadio.name = name;
  33105. boundingBoxesRadio.checked = initialState;
  33106. boundingBoxesRadio.style.display = "inline";
  33107. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  33108. boundingBoxesRadio.style.verticalAlign = "sub";
  33109. boundingBoxesRadio.addEventListener("change", function (evt) {
  33110. task(evt.target, tag);
  33111. });
  33112. label.appendChild(boundingBoxesRadio);
  33113. label.appendChild(document.createTextNode(title));
  33114. root.appendChild(label);
  33115. root.appendChild(document.createElement("br"));
  33116. };
  33117. DebugLayer.prototype._generateDOMelements = function () {
  33118. var _this = this;
  33119. this._globalDiv.id = "DebugLayer";
  33120. this._globalDiv.style.position = "absolute";
  33121. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  33122. this._globalDiv.style.fontSize = "14px";
  33123. this._globalDiv.style.color = "white";
  33124. // Drawing canvas
  33125. this._drawingCanvas = document.createElement("canvas");
  33126. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  33127. this._drawingCanvas.style.position = "absolute";
  33128. this._drawingCanvas.style.pointerEvents = "none";
  33129. this._drawingCanvas.style.backgroundColor = "transparent";
  33130. this._drawingContext = this._drawingCanvas.getContext("2d");
  33131. this._globalDiv.appendChild(this._drawingCanvas);
  33132. if (this._showUI) {
  33133. var background = "rgba(128, 128, 128, 0.4)";
  33134. var border = "rgb(180, 180, 180) solid 1px";
  33135. // Stats
  33136. this._statsDiv = document.createElement("div");
  33137. this._statsDiv.id = "DebugLayerStats";
  33138. this._statsDiv.style.border = border;
  33139. this._statsDiv.style.position = "absolute";
  33140. this._statsDiv.style.background = background;
  33141. this._statsDiv.style.padding = "0px 0px 0px 5px";
  33142. this._generateheader(this._statsDiv, "STATISTICS");
  33143. this._statsSubsetDiv = document.createElement("div");
  33144. this._statsSubsetDiv.style.paddingTop = "5px";
  33145. this._statsSubsetDiv.style.paddingBottom = "5px";
  33146. this._statsSubsetDiv.style.overflowY = "auto";
  33147. this._statsDiv.appendChild(this._statsSubsetDiv);
  33148. // Tree
  33149. this._treeDiv = document.createElement("div");
  33150. this._treeDiv.id = "DebugLayerTree";
  33151. this._treeDiv.style.border = border;
  33152. this._treeDiv.style.position = "absolute";
  33153. this._treeDiv.style.background = background;
  33154. this._treeDiv.style.padding = "0px 0px 0px 5px";
  33155. this._treeDiv.style.display = "none";
  33156. this._generateheader(this._treeDiv, "MESHES TREE");
  33157. this._treeSubsetDiv = document.createElement("div");
  33158. this._treeSubsetDiv.style.paddingTop = "5px";
  33159. this._treeSubsetDiv.style.paddingRight = "5px";
  33160. this._treeSubsetDiv.style.overflowY = "auto";
  33161. this._treeSubsetDiv.style.maxHeight = "300px";
  33162. this._treeDiv.appendChild(this._treeSubsetDiv);
  33163. this._needToRefreshMeshesTree = true;
  33164. // Logs
  33165. this._logDiv = document.createElement("div");
  33166. this._logDiv.style.border = border;
  33167. this._logDiv.id = "DebugLayerLogs";
  33168. this._logDiv.style.position = "absolute";
  33169. this._logDiv.style.background = background;
  33170. this._logDiv.style.padding = "0px 0px 0px 5px";
  33171. this._logDiv.style.display = "none";
  33172. this._generateheader(this._logDiv, "LOGS");
  33173. this._logSubsetDiv = document.createElement("div");
  33174. this._logSubsetDiv.style.height = "127px";
  33175. this._logSubsetDiv.style.paddingTop = "5px";
  33176. this._logSubsetDiv.style.overflowY = "auto";
  33177. this._logSubsetDiv.style.fontSize = "12px";
  33178. this._logSubsetDiv.style.fontFamily = "consolas";
  33179. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  33180. this._logDiv.appendChild(this._logSubsetDiv);
  33181. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  33182. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  33183. };
  33184. // Options
  33185. this._optionsDiv = document.createElement("div");
  33186. this._optionsDiv.id = "DebugLayerOptions";
  33187. this._optionsDiv.style.border = border;
  33188. this._optionsDiv.style.position = "absolute";
  33189. this._optionsDiv.style.background = background;
  33190. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  33191. this._optionsDiv.style.overflowY = "auto";
  33192. this._generateheader(this._optionsDiv, "OPTIONS");
  33193. this._optionsSubsetDiv = document.createElement("div");
  33194. this._optionsSubsetDiv.style.paddingTop = "5px";
  33195. this._optionsSubsetDiv.style.paddingBottom = "5px";
  33196. this._optionsSubsetDiv.style.overflowY = "auto";
  33197. this._optionsSubsetDiv.style.maxHeight = "200px";
  33198. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  33199. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  33200. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  33201. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  33202. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  33203. _this._displayTree = element.checked;
  33204. _this._needToRefreshMeshesTree = true;
  33205. });
  33206. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33207. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  33208. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  33209. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  33210. _this._labelsEnabled = element.checked;
  33211. if (!_this._labelsEnabled) {
  33212. _this._clearLabels();
  33213. }
  33214. });
  33215. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  33216. if (element.checked) {
  33217. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  33218. }
  33219. else {
  33220. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  33221. }
  33222. });
  33223. ;
  33224. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33225. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  33226. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  33227. if (element.checked) {
  33228. _this._scene.forceWireframe = false;
  33229. _this._scene.forcePointsCloud = false;
  33230. }
  33231. });
  33232. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  33233. if (element.checked) {
  33234. _this._scene.forceWireframe = true;
  33235. _this._scene.forcePointsCloud = false;
  33236. }
  33237. });
  33238. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  33239. if (element.checked) {
  33240. _this._scene.forceWireframe = false;
  33241. _this._scene.forcePointsCloud = true;
  33242. }
  33243. });
  33244. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33245. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  33246. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  33247. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  33248. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  33249. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  33250. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  33251. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  33252. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  33253. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  33254. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  33255. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  33256. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33257. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  33258. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  33259. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  33260. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  33261. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  33262. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  33263. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  33264. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  33265. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  33266. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  33267. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  33268. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  33269. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  33270. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  33271. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  33272. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  33273. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33274. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  33275. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  33276. if (element.checked) {
  33277. _this._scene.headphone = true;
  33278. }
  33279. });
  33280. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  33281. if (element.checked) {
  33282. _this._scene.headphone = false;
  33283. }
  33284. });
  33285. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  33286. _this._scene.audioEnabled = !element.checked;
  33287. });
  33288. }
  33289. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33290. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  33291. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  33292. if (!element.checked) {
  33293. _this._clearSkeletonViewers();
  33294. return;
  33295. }
  33296. for (var index = 0; index < _this._scene.meshes.length; index++) {
  33297. var mesh = _this._scene.meshes[index];
  33298. if (mesh.skeleton) {
  33299. var found = false;
  33300. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  33301. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  33302. found = true;
  33303. break;
  33304. }
  33305. }
  33306. if (found) {
  33307. continue;
  33308. }
  33309. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  33310. viewer.isEnabled = true;
  33311. _this._skeletonViewers.push(viewer);
  33312. }
  33313. }
  33314. });
  33315. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33316. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  33317. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  33318. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  33319. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  33320. if (_this._camera) {
  33321. console.log(_this._camera);
  33322. }
  33323. else {
  33324. console.warn("No camera defined, or debug layer created before camera creation!");
  33325. }
  33326. });
  33327. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  33328. this._globalDiv.appendChild(this._statsDiv);
  33329. this._globalDiv.appendChild(this._logDiv);
  33330. this._globalDiv.appendChild(this._optionsDiv);
  33331. this._globalDiv.appendChild(this._treeDiv);
  33332. }
  33333. };
  33334. DebugLayer.prototype._displayStats = function () {
  33335. var scene = this._scene;
  33336. var engine = scene.getEngine();
  33337. var glInfo = engine.getGlInfo();
  33338. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  33339. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33340. + "<b>Count</b><br>"
  33341. + "Total meshes: " + scene.meshes.length + "<br>"
  33342. + "Total lights: " + scene.lights.length + "<br>"
  33343. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  33344. + "Total materials: " + scene.materials.length + "<br>"
  33345. + "Total textures: " + scene.textures.length + "<br>"
  33346. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  33347. + "Active indices: " + scene.getActiveIndices() + "<br>"
  33348. + "Active bones: " + scene.getActiveBones() + "<br>"
  33349. + "Active particles: " + scene.getActiveParticles() + "<br>"
  33350. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  33351. + "<b>Duration</b><br>"
  33352. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  33353. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  33354. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  33355. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  33356. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  33357. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  33358. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  33359. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  33360. + "</div>"
  33361. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33362. + "<b>Extensions</b><br>"
  33363. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  33364. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  33365. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  33366. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  33367. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  33368. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  33369. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  33370. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  33371. + "</div><br>"
  33372. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  33373. + "<b>Caps.</b><br>"
  33374. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  33375. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  33376. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  33377. + "<b>Info</b><br>"
  33378. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  33379. + glInfo.version + "<br>"
  33380. + "</div><br>"
  33381. + glInfo.renderer + "<br>";
  33382. if (this.customStatsFunction) {
  33383. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  33384. }
  33385. };
  33386. return DebugLayer;
  33387. })();
  33388. BABYLON.DebugLayer = DebugLayer;
  33389. })(BABYLON || (BABYLON = {}));
  33390. var BABYLON;
  33391. (function (BABYLON) {
  33392. var DefaultLoadingScreen = (function () {
  33393. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  33394. var _this = this;
  33395. if (_loadingText === void 0) { _loadingText = ""; }
  33396. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  33397. this._renderingCanvas = _renderingCanvas;
  33398. this._loadingText = _loadingText;
  33399. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  33400. // Resize
  33401. this._resizeLoadingUI = function () {
  33402. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  33403. _this._loadingDiv.style.position = "absolute";
  33404. _this._loadingDiv.style.left = canvasRect.left + "px";
  33405. _this._loadingDiv.style.top = canvasRect.top + "px";
  33406. _this._loadingDiv.style.width = canvasRect.width + "px";
  33407. _this._loadingDiv.style.height = canvasRect.height + "px";
  33408. };
  33409. }
  33410. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  33411. var _this = this;
  33412. if (this._loadingDiv) {
  33413. // Do not add a loading screen if there is already one
  33414. return;
  33415. }
  33416. this._loadingDiv = document.createElement("div");
  33417. this._loadingDiv.id = "babylonjsLoadingDiv";
  33418. this._loadingDiv.style.opacity = "0";
  33419. this._loadingDiv.style.transition = "opacity 1.5s ease";
  33420. // Loading text
  33421. this._loadingTextDiv = document.createElement("div");
  33422. this._loadingTextDiv.style.position = "absolute";
  33423. this._loadingTextDiv.style.left = "0";
  33424. this._loadingTextDiv.style.top = "50%";
  33425. this._loadingTextDiv.style.marginTop = "80px";
  33426. this._loadingTextDiv.style.width = "100%";
  33427. this._loadingTextDiv.style.height = "20px";
  33428. this._loadingTextDiv.style.fontFamily = "Arial";
  33429. this._loadingTextDiv.style.fontSize = "14px";
  33430. this._loadingTextDiv.style.color = "white";
  33431. this._loadingTextDiv.style.textAlign = "center";
  33432. this._loadingTextDiv.innerHTML = "Loading";
  33433. this._loadingDiv.appendChild(this._loadingTextDiv);
  33434. //set the predefined text
  33435. this._loadingTextDiv.innerHTML = this._loadingText;
  33436. // Loading img
  33437. var imgBack = new Image();
  33438. 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==";
  33439. imgBack.style.position = "absolute";
  33440. imgBack.style.left = "50%";
  33441. imgBack.style.top = "50%";
  33442. imgBack.style.marginLeft = "-50px";
  33443. imgBack.style.marginTop = "-50px";
  33444. imgBack.style.transition = "transform 1.0s ease";
  33445. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  33446. var deg = 360;
  33447. var onTransitionEnd = function () {
  33448. deg += 360;
  33449. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  33450. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  33451. };
  33452. imgBack.addEventListener("transitionend", onTransitionEnd);
  33453. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  33454. this._loadingDiv.appendChild(imgBack);
  33455. // front image
  33456. var imgFront = new Image();
  33457. 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=";
  33458. imgFront.style.position = "absolute";
  33459. imgFront.style.left = "50%";
  33460. imgFront.style.top = "50%";
  33461. imgFront.style.marginLeft = "-50px";
  33462. imgFront.style.marginTop = "-50px";
  33463. this._loadingDiv.appendChild(imgFront);
  33464. this._resizeLoadingUI();
  33465. window.addEventListener("resize", this._resizeLoadingUI);
  33466. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33467. document.body.appendChild(this._loadingDiv);
  33468. setTimeout(function () {
  33469. _this._loadingDiv.style.opacity = "1";
  33470. imgBack.style.transform = "rotateZ(360deg)";
  33471. imgBack.style.webkitTransform = "rotateZ(360deg)";
  33472. }, 0);
  33473. };
  33474. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  33475. var _this = this;
  33476. if (!this._loadingDiv) {
  33477. return;
  33478. }
  33479. var onTransitionEnd = function () {
  33480. if (!_this._loadingDiv) {
  33481. return;
  33482. }
  33483. document.body.removeChild(_this._loadingDiv);
  33484. window.removeEventListener("resize", _this._resizeLoadingUI);
  33485. _this._loadingDiv = null;
  33486. };
  33487. this._loadingDiv.style.opacity = "0";
  33488. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  33489. };
  33490. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  33491. set: function (text) {
  33492. this._loadingText = text;
  33493. if (this._loadingTextDiv) {
  33494. this._loadingTextDiv.innerHTML = this._loadingText;
  33495. }
  33496. },
  33497. enumerable: true,
  33498. configurable: true
  33499. });
  33500. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  33501. get: function () {
  33502. return this._loadingDivBackgroundColor;
  33503. },
  33504. set: function (color) {
  33505. this._loadingDivBackgroundColor = color;
  33506. if (!this._loadingDiv) {
  33507. return;
  33508. }
  33509. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  33510. },
  33511. enumerable: true,
  33512. configurable: true
  33513. });
  33514. return DefaultLoadingScreen;
  33515. })();
  33516. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33517. })(BABYLON || (BABYLON = {}));
  33518. var BABYLON;
  33519. (function (BABYLON) {
  33520. var AudioEngine = (function () {
  33521. function AudioEngine() {
  33522. this._audioContext = null;
  33523. this._audioContextInitialized = false;
  33524. this.canUseWebAudio = false;
  33525. this.WarnedWebAudioUnsupported = false;
  33526. this.unlocked = false;
  33527. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33528. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33529. this.canUseWebAudio = true;
  33530. }
  33531. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33532. this._unlockiOSaudio();
  33533. }
  33534. else {
  33535. this.unlocked = true;
  33536. }
  33537. }
  33538. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33539. get: function () {
  33540. if (!this._audioContextInitialized) {
  33541. this._initializeAudioContext();
  33542. }
  33543. return this._audioContext;
  33544. },
  33545. enumerable: true,
  33546. configurable: true
  33547. });
  33548. AudioEngine.prototype._unlockiOSaudio = function () {
  33549. var _this = this;
  33550. var unlockaudio = function () {
  33551. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33552. var source = _this.audioContext.createBufferSource();
  33553. source.buffer = buffer;
  33554. source.connect(_this.audioContext.destination);
  33555. source.start(0);
  33556. setTimeout(function () {
  33557. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33558. _this.unlocked = true;
  33559. window.removeEventListener('touchend', unlockaudio, false);
  33560. if (_this.onAudioUnlocked) {
  33561. _this.onAudioUnlocked();
  33562. }
  33563. }
  33564. }, 0);
  33565. };
  33566. window.addEventListener('touchend', unlockaudio, false);
  33567. };
  33568. AudioEngine.prototype._initializeAudioContext = function () {
  33569. try {
  33570. if (this.canUseWebAudio) {
  33571. this._audioContext = new AudioContext();
  33572. // create a global volume gain node
  33573. this.masterGain = this._audioContext.createGain();
  33574. this.masterGain.gain.value = 1;
  33575. this.masterGain.connect(this._audioContext.destination);
  33576. this._audioContextInitialized = true;
  33577. }
  33578. }
  33579. catch (e) {
  33580. this.canUseWebAudio = false;
  33581. BABYLON.Tools.Error("Web Audio: " + e.message);
  33582. }
  33583. };
  33584. AudioEngine.prototype.dispose = function () {
  33585. if (this.canUseWebAudio && this._audioContextInitialized) {
  33586. if (this._connectedAnalyser) {
  33587. this._connectedAnalyser.stopDebugCanvas();
  33588. this._connectedAnalyser.dispose();
  33589. this.masterGain.disconnect();
  33590. this.masterGain.connect(this._audioContext.destination);
  33591. this._connectedAnalyser = null;
  33592. }
  33593. this.masterGain.gain.value = 1;
  33594. }
  33595. this.WarnedWebAudioUnsupported = false;
  33596. };
  33597. AudioEngine.prototype.getGlobalVolume = function () {
  33598. if (this.canUseWebAudio && this._audioContextInitialized) {
  33599. return this.masterGain.gain.value;
  33600. }
  33601. else {
  33602. return -1;
  33603. }
  33604. };
  33605. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33606. if (this.canUseWebAudio && this._audioContextInitialized) {
  33607. this.masterGain.gain.value = newVolume;
  33608. }
  33609. };
  33610. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33611. if (this._connectedAnalyser) {
  33612. this._connectedAnalyser.stopDebugCanvas();
  33613. }
  33614. if (this.canUseWebAudio && this._audioContextInitialized) {
  33615. this._connectedAnalyser = analyser;
  33616. this.masterGain.disconnect();
  33617. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33618. }
  33619. };
  33620. return AudioEngine;
  33621. })();
  33622. BABYLON.AudioEngine = AudioEngine;
  33623. })(BABYLON || (BABYLON = {}));
  33624. var BABYLON;
  33625. (function (BABYLON) {
  33626. var Sound = (function () {
  33627. /**
  33628. * Create a sound and attach it to a scene
  33629. * @param name Name of your sound
  33630. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33631. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33632. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33633. */
  33634. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33635. var _this = this;
  33636. this.autoplay = false;
  33637. this.loop = false;
  33638. this.useCustomAttenuation = false;
  33639. this.spatialSound = false;
  33640. this.refDistance = 1;
  33641. this.rolloffFactor = 1;
  33642. this.maxDistance = 100;
  33643. this.distanceModel = "linear";
  33644. this._panningModel = "equalpower";
  33645. this._playbackRate = 1;
  33646. this._streaming = false;
  33647. this._startTime = 0;
  33648. this._startOffset = 0;
  33649. this._position = BABYLON.Vector3.Zero();
  33650. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33651. this._volume = 1;
  33652. this._isLoaded = false;
  33653. this._isReadyToPlay = false;
  33654. this.isPlaying = false;
  33655. this.isPaused = false;
  33656. this._isDirectional = false;
  33657. // Used if you'd like to create a directional sound.
  33658. // If not set, the sound will be omnidirectional
  33659. this._coneInnerAngle = 360;
  33660. this._coneOuterAngle = 360;
  33661. this._coneOuterGain = 0;
  33662. this._isOutputConnected = false;
  33663. this.name = name;
  33664. this._scene = scene;
  33665. this._readyToPlayCallback = readyToPlayCallback;
  33666. // Default custom attenuation function is a linear attenuation
  33667. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33668. if (currentDistance < maxDistance) {
  33669. return currentVolume * (1 - currentDistance / maxDistance);
  33670. }
  33671. else {
  33672. return 0;
  33673. }
  33674. };
  33675. if (options) {
  33676. this.autoplay = options.autoplay || false;
  33677. this.loop = options.loop || false;
  33678. // if volume === 0, we need another way to check this option
  33679. if (options.volume !== undefined) {
  33680. this._volume = options.volume;
  33681. }
  33682. this.spatialSound = options.spatialSound || false;
  33683. this.maxDistance = options.maxDistance || 100;
  33684. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33685. this.rolloffFactor = options.rolloffFactor || 1;
  33686. this.refDistance = options.refDistance || 1;
  33687. this.distanceModel = options.distanceModel || "linear";
  33688. this._playbackRate = options.playbackRate || 1;
  33689. this._streaming = options.streaming || false;
  33690. }
  33691. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33692. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33693. this._soundGain.gain.value = this._volume;
  33694. this._inputAudioNode = this._soundGain;
  33695. this._ouputAudioNode = this._soundGain;
  33696. if (this.spatialSound) {
  33697. this._createSpatialParameters();
  33698. }
  33699. this._scene.mainSoundTrack.AddSound(this);
  33700. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33701. if (urlOrArrayBuffer) {
  33702. // If it's an URL
  33703. if (typeof (urlOrArrayBuffer) === "string") {
  33704. // Loading sound using XHR2
  33705. if (!this._streaming) {
  33706. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33707. }
  33708. else {
  33709. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33710. this._htmlAudioElement.controls = false;
  33711. this._htmlAudioElement.loop = this.loop;
  33712. this._htmlAudioElement.crossOrigin = "anonymous";
  33713. this._htmlAudioElement.preload = "auto";
  33714. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33715. _this._isReadyToPlay = true;
  33716. if (_this.autoplay) {
  33717. _this.play();
  33718. }
  33719. if (_this._readyToPlayCallback) {
  33720. _this._readyToPlayCallback();
  33721. }
  33722. });
  33723. document.body.appendChild(this._htmlAudioElement);
  33724. }
  33725. }
  33726. else {
  33727. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33728. if (urlOrArrayBuffer.byteLength > 0) {
  33729. this._soundLoaded(urlOrArrayBuffer);
  33730. }
  33731. }
  33732. else {
  33733. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33734. }
  33735. }
  33736. }
  33737. }
  33738. else {
  33739. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33740. this._scene.mainSoundTrack.AddSound(this);
  33741. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33742. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33743. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33744. }
  33745. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33746. if (this._readyToPlayCallback) {
  33747. window.setTimeout(function () {
  33748. _this._readyToPlayCallback();
  33749. }, 1000);
  33750. }
  33751. }
  33752. }
  33753. Sound.prototype.dispose = function () {
  33754. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33755. if (this.isPlaying) {
  33756. this.stop();
  33757. }
  33758. this._isReadyToPlay = false;
  33759. if (this.soundTrackId === -1) {
  33760. this._scene.mainSoundTrack.RemoveSound(this);
  33761. }
  33762. else {
  33763. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33764. }
  33765. if (this._soundGain) {
  33766. this._soundGain.disconnect();
  33767. this._soundGain = null;
  33768. }
  33769. if (this._soundPanner) {
  33770. this._soundPanner.disconnect();
  33771. this._soundPanner = null;
  33772. }
  33773. if (this._soundSource) {
  33774. this._soundSource.disconnect();
  33775. this._soundSource = null;
  33776. }
  33777. this._audioBuffer = null;
  33778. if (this._htmlAudioElement) {
  33779. this._htmlAudioElement.pause();
  33780. this._htmlAudioElement.src = "";
  33781. document.body.removeChild(this._htmlAudioElement);
  33782. }
  33783. if (this._connectedMesh) {
  33784. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33785. this._connectedMesh = null;
  33786. }
  33787. }
  33788. };
  33789. Sound.prototype._soundLoaded = function (audioData) {
  33790. var _this = this;
  33791. this._isLoaded = true;
  33792. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33793. _this._audioBuffer = buffer;
  33794. _this._isReadyToPlay = true;
  33795. if (_this.autoplay) {
  33796. _this.play();
  33797. }
  33798. if (_this._readyToPlayCallback) {
  33799. _this._readyToPlayCallback();
  33800. }
  33801. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33802. };
  33803. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33804. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33805. this._audioBuffer = audioBuffer;
  33806. this._isReadyToPlay = true;
  33807. }
  33808. };
  33809. Sound.prototype.updateOptions = function (options) {
  33810. if (options) {
  33811. this.loop = options.loop || this.loop;
  33812. this.maxDistance = options.maxDistance || this.maxDistance;
  33813. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33814. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33815. this.refDistance = options.refDistance || this.refDistance;
  33816. this.distanceModel = options.distanceModel || this.distanceModel;
  33817. this._playbackRate = options.playbackRate || this._playbackRate;
  33818. this._updateSpatialParameters();
  33819. if (this.isPlaying) {
  33820. if (this._streaming) {
  33821. this._htmlAudioElement.playbackRate = this._playbackRate;
  33822. }
  33823. else {
  33824. this._soundSource.playbackRate.value = this._playbackRate;
  33825. }
  33826. }
  33827. }
  33828. };
  33829. Sound.prototype._createSpatialParameters = function () {
  33830. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33831. if (this._scene.headphone) {
  33832. this._panningModel = "HRTF";
  33833. }
  33834. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33835. this._updateSpatialParameters();
  33836. this._soundPanner.connect(this._ouputAudioNode);
  33837. this._inputAudioNode = this._soundPanner;
  33838. }
  33839. };
  33840. Sound.prototype._updateSpatialParameters = function () {
  33841. if (this.spatialSound) {
  33842. if (this.useCustomAttenuation) {
  33843. // Tricks to disable in a way embedded Web Audio attenuation
  33844. this._soundPanner.distanceModel = "linear";
  33845. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33846. this._soundPanner.refDistance = 1;
  33847. this._soundPanner.rolloffFactor = 1;
  33848. this._soundPanner.panningModel = this._panningModel;
  33849. }
  33850. else {
  33851. this._soundPanner.distanceModel = this.distanceModel;
  33852. this._soundPanner.maxDistance = this.maxDistance;
  33853. this._soundPanner.refDistance = this.refDistance;
  33854. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33855. this._soundPanner.panningModel = this._panningModel;
  33856. }
  33857. }
  33858. };
  33859. Sound.prototype.switchPanningModelToHRTF = function () {
  33860. this._panningModel = "HRTF";
  33861. this._switchPanningModel();
  33862. };
  33863. Sound.prototype.switchPanningModelToEqualPower = function () {
  33864. this._panningModel = "equalpower";
  33865. this._switchPanningModel();
  33866. };
  33867. Sound.prototype._switchPanningModel = function () {
  33868. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33869. this._soundPanner.panningModel = this._panningModel;
  33870. }
  33871. };
  33872. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33873. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33874. if (this._isOutputConnected) {
  33875. this._ouputAudioNode.disconnect();
  33876. }
  33877. this._ouputAudioNode.connect(soundTrackAudioNode);
  33878. this._isOutputConnected = true;
  33879. }
  33880. };
  33881. /**
  33882. * Transform this sound into a directional source
  33883. * @param coneInnerAngle Size of the inner cone in degree
  33884. * @param coneOuterAngle Size of the outer cone in degree
  33885. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33886. */
  33887. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33888. if (coneOuterAngle < coneInnerAngle) {
  33889. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33890. return;
  33891. }
  33892. this._coneInnerAngle = coneInnerAngle;
  33893. this._coneOuterAngle = coneOuterAngle;
  33894. this._coneOuterGain = coneOuterGain;
  33895. this._isDirectional = true;
  33896. if (this.isPlaying && this.loop) {
  33897. this.stop();
  33898. this.play();
  33899. }
  33900. };
  33901. Sound.prototype.setPosition = function (newPosition) {
  33902. this._position = newPosition;
  33903. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33904. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33905. }
  33906. };
  33907. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33908. this._localDirection = newLocalDirection;
  33909. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33910. this._updateDirection();
  33911. }
  33912. };
  33913. Sound.prototype._updateDirection = function () {
  33914. var mat = this._connectedMesh.getWorldMatrix();
  33915. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33916. direction.normalize();
  33917. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33918. };
  33919. Sound.prototype.updateDistanceFromListener = function () {
  33920. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33921. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33922. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33923. }
  33924. };
  33925. Sound.prototype.setAttenuationFunction = function (callback) {
  33926. this._customAttenuationFunction = callback;
  33927. };
  33928. /**
  33929. * Play the sound
  33930. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33931. */
  33932. Sound.prototype.play = function (time) {
  33933. var _this = this;
  33934. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33935. try {
  33936. if (this._startOffset < 0) {
  33937. time = -this._startOffset;
  33938. this._startOffset = 0;
  33939. }
  33940. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33941. if (!this._soundSource || !this._streamingSource) {
  33942. if (this.spatialSound) {
  33943. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33944. if (this._isDirectional) {
  33945. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33946. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33947. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33948. if (this._connectedMesh) {
  33949. this._updateDirection();
  33950. }
  33951. else {
  33952. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33953. }
  33954. }
  33955. }
  33956. }
  33957. if (this._streaming) {
  33958. if (!this._streamingSource) {
  33959. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33960. this._htmlAudioElement.onended = function () { _this._onended(); };
  33961. this._htmlAudioElement.playbackRate = this._playbackRate;
  33962. }
  33963. this._streamingSource.disconnect();
  33964. this._streamingSource.connect(this._inputAudioNode);
  33965. this._htmlAudioElement.play();
  33966. }
  33967. else {
  33968. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33969. this._soundSource.buffer = this._audioBuffer;
  33970. this._soundSource.connect(this._inputAudioNode);
  33971. this._soundSource.loop = this.loop;
  33972. this._soundSource.playbackRate.value = this._playbackRate;
  33973. this._soundSource.onended = function () { _this._onended(); };
  33974. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33975. }
  33976. this._startTime = startTime;
  33977. this.isPlaying = true;
  33978. this.isPaused = false;
  33979. }
  33980. catch (ex) {
  33981. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33982. }
  33983. }
  33984. };
  33985. Sound.prototype._onended = function () {
  33986. this.isPlaying = false;
  33987. if (this.onended) {
  33988. this.onended();
  33989. }
  33990. };
  33991. /**
  33992. * Stop the sound
  33993. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33994. */
  33995. Sound.prototype.stop = function (time) {
  33996. if (this.isPlaying) {
  33997. if (this._streaming) {
  33998. this._htmlAudioElement.pause();
  33999. // Test needed for Firefox or it will generate an Invalid State Error
  34000. if (this._htmlAudioElement.currentTime > 0) {
  34001. this._htmlAudioElement.currentTime = 0;
  34002. }
  34003. }
  34004. else {
  34005. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  34006. this._soundSource.stop(stopTime);
  34007. if (!this.isPaused) {
  34008. this._startOffset = 0;
  34009. }
  34010. }
  34011. this.isPlaying = false;
  34012. }
  34013. };
  34014. Sound.prototype.pause = function () {
  34015. if (this.isPlaying) {
  34016. this.isPaused = true;
  34017. if (this._streaming) {
  34018. this._htmlAudioElement.pause();
  34019. }
  34020. else {
  34021. this.stop(0);
  34022. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  34023. }
  34024. }
  34025. };
  34026. Sound.prototype.setVolume = function (newVolume, time) {
  34027. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34028. if (time) {
  34029. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  34030. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  34031. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  34032. }
  34033. else {
  34034. this._soundGain.gain.value = newVolume;
  34035. }
  34036. }
  34037. this._volume = newVolume;
  34038. };
  34039. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  34040. this._playbackRate = newPlaybackRate;
  34041. if (this.isPlaying) {
  34042. if (this._streaming) {
  34043. this._htmlAudioElement.playbackRate = this._playbackRate;
  34044. }
  34045. else {
  34046. this._soundSource.playbackRate.value = this._playbackRate;
  34047. }
  34048. }
  34049. };
  34050. Sound.prototype.getVolume = function () {
  34051. return this._volume;
  34052. };
  34053. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  34054. var _this = this;
  34055. if (this._connectedMesh) {
  34056. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  34057. this._registerFunc = null;
  34058. }
  34059. this._connectedMesh = meshToConnectTo;
  34060. if (!this.spatialSound) {
  34061. this.spatialSound = true;
  34062. this._createSpatialParameters();
  34063. if (this.isPlaying && this.loop) {
  34064. this.stop();
  34065. this.play();
  34066. }
  34067. }
  34068. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  34069. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  34070. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  34071. };
  34072. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  34073. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  34074. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  34075. this._updateDirection();
  34076. }
  34077. };
  34078. Sound.prototype.clone = function () {
  34079. var _this = this;
  34080. if (!this._streaming) {
  34081. var setBufferAndRun = function () {
  34082. if (_this._isReadyToPlay) {
  34083. clonedSound._audioBuffer = _this.getAudioBuffer();
  34084. clonedSound._isReadyToPlay = true;
  34085. if (clonedSound.autoplay) {
  34086. clonedSound.play();
  34087. }
  34088. }
  34089. else {
  34090. window.setTimeout(setBufferAndRun, 300);
  34091. }
  34092. };
  34093. var currentOptions = {
  34094. autoplay: this.autoplay, loop: this.loop,
  34095. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  34096. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  34097. refDistance: this.refDistance, distanceModel: this.distanceModel
  34098. };
  34099. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  34100. if (this.useCustomAttenuation) {
  34101. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  34102. }
  34103. clonedSound.setPosition(this._position);
  34104. clonedSound.setPlaybackRate(this._playbackRate);
  34105. setBufferAndRun();
  34106. return clonedSound;
  34107. }
  34108. else {
  34109. return null;
  34110. }
  34111. };
  34112. Sound.prototype.getAudioBuffer = function () {
  34113. return this._audioBuffer;
  34114. };
  34115. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  34116. var soundName = parsedSound.name;
  34117. var soundUrl;
  34118. if (parsedSound.url) {
  34119. soundUrl = rootUrl + parsedSound.url;
  34120. }
  34121. else {
  34122. soundUrl = rootUrl + soundName;
  34123. }
  34124. var options = {
  34125. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  34126. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  34127. rolloffFactor: parsedSound.rolloffFactor,
  34128. refDistance: parsedSound.refDistance,
  34129. distanceModel: parsedSound.distanceModel,
  34130. playbackRate: parsedSound.playbackRate
  34131. };
  34132. var newSound;
  34133. if (!sourceSound) {
  34134. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  34135. scene._addPendingData(newSound);
  34136. }
  34137. else {
  34138. var setBufferAndRun = function () {
  34139. if (sourceSound._isReadyToPlay) {
  34140. newSound._audioBuffer = sourceSound.getAudioBuffer();
  34141. newSound._isReadyToPlay = true;
  34142. if (newSound.autoplay) {
  34143. newSound.play();
  34144. }
  34145. }
  34146. else {
  34147. window.setTimeout(setBufferAndRun, 300);
  34148. }
  34149. };
  34150. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  34151. setBufferAndRun();
  34152. }
  34153. if (parsedSound.position) {
  34154. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  34155. newSound.setPosition(soundPosition);
  34156. }
  34157. if (parsedSound.isDirectional) {
  34158. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  34159. if (parsedSound.localDirectionToMesh) {
  34160. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  34161. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  34162. }
  34163. }
  34164. if (parsedSound.connectedMeshId) {
  34165. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  34166. if (connectedMesh) {
  34167. newSound.attachToMesh(connectedMesh);
  34168. }
  34169. }
  34170. return newSound;
  34171. };
  34172. return Sound;
  34173. })();
  34174. BABYLON.Sound = Sound;
  34175. })(BABYLON || (BABYLON = {}));
  34176. var BABYLON;
  34177. (function (BABYLON) {
  34178. var SoundTrack = (function () {
  34179. function SoundTrack(scene, options) {
  34180. this.id = -1;
  34181. this._isMainTrack = false;
  34182. this._isInitialized = false;
  34183. this._scene = scene;
  34184. this.soundCollection = new Array();
  34185. this._options = options;
  34186. if (!this._isMainTrack) {
  34187. this._scene.soundTracks.push(this);
  34188. this.id = this._scene.soundTracks.length - 1;
  34189. }
  34190. }
  34191. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  34192. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34193. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  34194. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  34195. if (this._options) {
  34196. if (this._options.volume) {
  34197. this._outputAudioNode.gain.value = this._options.volume;
  34198. }
  34199. if (this._options.mainTrack) {
  34200. this._isMainTrack = this._options.mainTrack;
  34201. }
  34202. }
  34203. this._isInitialized = true;
  34204. }
  34205. };
  34206. SoundTrack.prototype.dispose = function () {
  34207. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34208. if (this._connectedAnalyser) {
  34209. this._connectedAnalyser.stopDebugCanvas();
  34210. }
  34211. while (this.soundCollection.length) {
  34212. this.soundCollection[0].dispose();
  34213. }
  34214. if (this._outputAudioNode) {
  34215. this._outputAudioNode.disconnect();
  34216. }
  34217. this._outputAudioNode = null;
  34218. }
  34219. };
  34220. SoundTrack.prototype.AddSound = function (sound) {
  34221. if (!this._isInitialized) {
  34222. this._initializeSoundTrackAudioGraph();
  34223. }
  34224. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34225. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  34226. }
  34227. if (sound.soundTrackId) {
  34228. if (sound.soundTrackId === -1) {
  34229. this._scene.mainSoundTrack.RemoveSound(sound);
  34230. }
  34231. else {
  34232. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  34233. }
  34234. }
  34235. this.soundCollection.push(sound);
  34236. sound.soundTrackId = this.id;
  34237. };
  34238. SoundTrack.prototype.RemoveSound = function (sound) {
  34239. var index = this.soundCollection.indexOf(sound);
  34240. if (index !== -1) {
  34241. this.soundCollection.splice(index, 1);
  34242. }
  34243. };
  34244. SoundTrack.prototype.setVolume = function (newVolume) {
  34245. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34246. this._outputAudioNode.gain.value = newVolume;
  34247. }
  34248. };
  34249. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  34250. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34251. for (var i = 0; i < this.soundCollection.length; i++) {
  34252. this.soundCollection[i].switchPanningModelToHRTF();
  34253. }
  34254. }
  34255. };
  34256. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  34257. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34258. for (var i = 0; i < this.soundCollection.length; i++) {
  34259. this.soundCollection[i].switchPanningModelToEqualPower();
  34260. }
  34261. }
  34262. };
  34263. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  34264. if (this._connectedAnalyser) {
  34265. this._connectedAnalyser.stopDebugCanvas();
  34266. }
  34267. this._connectedAnalyser = analyser;
  34268. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  34269. this._outputAudioNode.disconnect();
  34270. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  34271. }
  34272. };
  34273. return SoundTrack;
  34274. })();
  34275. BABYLON.SoundTrack = SoundTrack;
  34276. })(BABYLON || (BABYLON = {}));
  34277. var BABYLON;
  34278. (function (BABYLON) {
  34279. var SIMDVector3 = (function () {
  34280. function SIMDVector3() {
  34281. }
  34282. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  34283. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  34284. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34285. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34286. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34287. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34288. 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));
  34289. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34290. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34291. };
  34292. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  34293. var v0 = SIMD.float32x4.splat(x);
  34294. var v1 = SIMD.float32x4.splat(y);
  34295. var v2 = SIMD.float32x4.splat(z);
  34296. var m0 = SIMD.float32x4.load(transformation.m, 0);
  34297. var m1 = SIMD.float32x4.load(transformation.m, 4);
  34298. var m2 = SIMD.float32x4.load(transformation.m, 8);
  34299. var m3 = SIMD.float32x4.load(transformation.m, 12);
  34300. 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));
  34301. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  34302. SIMD.float32x4.storeXYZ(result._data, 0, r);
  34303. };
  34304. return SIMDVector3;
  34305. })();
  34306. BABYLON.SIMDVector3 = SIMDVector3;
  34307. var SIMDMatrix = (function () {
  34308. function SIMDMatrix() {
  34309. }
  34310. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  34311. if (offset === void 0) { offset = 0; }
  34312. var tm = this.m;
  34313. var om = other.m;
  34314. var om0 = SIMD.float32x4.load(om, 0);
  34315. var om1 = SIMD.float32x4.load(om, 4);
  34316. var om2 = SIMD.float32x4.load(om, 8);
  34317. var om3 = SIMD.float32x4.load(om, 12);
  34318. var tm0 = SIMD.float32x4.load(tm, 0);
  34319. 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)))));
  34320. var tm1 = SIMD.float32x4.load(tm, 4);
  34321. 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)))));
  34322. var tm2 = SIMD.float32x4.load(tm, 8);
  34323. 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)))));
  34324. var tm3 = SIMD.float32x4.load(tm, 12);
  34325. 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)))));
  34326. };
  34327. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  34328. var src = this.m;
  34329. var dest = other.m;
  34330. var row0, row1, row2, row3;
  34331. var tmp1;
  34332. var minor0, minor1, minor2, minor3;
  34333. var det;
  34334. // Load the 4 rows
  34335. var src0 = SIMD.float32x4.load(src, 0);
  34336. var src1 = SIMD.float32x4.load(src, 4);
  34337. var src2 = SIMD.float32x4.load(src, 8);
  34338. var src3 = SIMD.float32x4.load(src, 12);
  34339. // Transpose the source matrix. Sort of. Not a true transpose operation
  34340. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34341. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34342. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  34343. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  34344. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34345. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34346. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  34347. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  34348. // This is a true transposition, but it will lead to an incorrect result
  34349. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  34350. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  34351. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34352. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34353. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  34354. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  34355. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  34356. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  34357. // ----
  34358. tmp1 = SIMD.float32x4.mul(row2, row3);
  34359. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34360. minor0 = SIMD.float32x4.mul(row1, tmp1);
  34361. minor1 = SIMD.float32x4.mul(row0, tmp1);
  34362. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34363. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  34364. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  34365. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  34366. // ----
  34367. tmp1 = SIMD.float32x4.mul(row1, row2);
  34368. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34369. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  34370. minor3 = SIMD.float32x4.mul(row0, tmp1);
  34371. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34372. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  34373. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  34374. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  34375. // ----
  34376. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  34377. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34378. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  34379. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  34380. minor2 = SIMD.float32x4.mul(row0, tmp1);
  34381. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34382. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  34383. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  34384. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  34385. // ----
  34386. tmp1 = SIMD.float32x4.mul(row0, row1);
  34387. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34388. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  34389. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  34390. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34391. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  34392. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  34393. // ----
  34394. tmp1 = SIMD.float32x4.mul(row0, row3);
  34395. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34396. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  34397. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  34398. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34399. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  34400. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  34401. // ----
  34402. tmp1 = SIMD.float32x4.mul(row0, row2);
  34403. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  34404. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  34405. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  34406. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  34407. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  34408. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  34409. // Compute determinant
  34410. det = SIMD.float32x4.mul(row0, minor0);
  34411. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  34412. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  34413. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  34414. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  34415. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  34416. // These shuffles aren't necessary if the faulty transposition is done
  34417. // up at the top of this function.
  34418. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  34419. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  34420. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  34421. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  34422. // Compute final values by multiplying with 1/det
  34423. minor0 = SIMD.float32x4.mul(det, minor0);
  34424. minor1 = SIMD.float32x4.mul(det, minor1);
  34425. minor2 = SIMD.float32x4.mul(det, minor2);
  34426. minor3 = SIMD.float32x4.mul(det, minor3);
  34427. SIMD.float32x4.store(dest, 0, minor0);
  34428. SIMD.float32x4.store(dest, 4, minor1);
  34429. SIMD.float32x4.store(dest, 8, minor2);
  34430. SIMD.float32x4.store(dest, 12, minor3);
  34431. return this;
  34432. };
  34433. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  34434. var out = result.m;
  34435. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  34436. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  34437. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  34438. // cc.kmVec3Subtract(f, pCenter, pEye);
  34439. var f = SIMD.float32x4.sub(center, eye);
  34440. // cc.kmVec3Normalize(f, f);
  34441. var tmp = SIMD.float32x4.mul(f, f);
  34442. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34443. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34444. // cc.kmVec3Assign(up, pUp);
  34445. // cc.kmVec3Normalize(up, up);
  34446. tmp = SIMD.float32x4.mul(up, up);
  34447. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34448. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34449. // cc.kmVec3Cross(s, f, up);
  34450. 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)));
  34451. // cc.kmVec3Normalize(s, s);
  34452. tmp = SIMD.float32x4.mul(s, s);
  34453. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34454. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34455. // cc.kmVec3Cross(u, s, f);
  34456. 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)));
  34457. // cc.kmVec3Normalize(s, s);
  34458. tmp = SIMD.float32x4.mul(s, s);
  34459. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  34460. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  34461. var zero = SIMD.float32x4.splat(0.0);
  34462. s = SIMD.float32x4.neg(s);
  34463. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  34464. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  34465. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34466. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  34467. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  34468. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  34469. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  34470. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  34471. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  34472. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  34473. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  34474. var b3 = SIMD.float32x4.neg(eye);
  34475. b3 = SIMD.float32x4.withW(b3, 1.0);
  34476. 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)))));
  34477. 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)))));
  34478. 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)))));
  34479. 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)))));
  34480. };
  34481. return SIMDMatrix;
  34482. })();
  34483. BABYLON.SIMDMatrix = SIMDMatrix;
  34484. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  34485. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  34486. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  34487. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  34488. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  34489. var SIMDHelper = (function () {
  34490. function SIMDHelper() {
  34491. }
  34492. Object.defineProperty(SIMDHelper, "IsEnabled", {
  34493. get: function () {
  34494. return SIMDHelper._isEnabled;
  34495. },
  34496. enumerable: true,
  34497. configurable: true
  34498. });
  34499. SIMDHelper.DisableSIMD = function () {
  34500. // Replace functions
  34501. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  34502. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  34503. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  34504. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  34505. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  34506. SIMDHelper._isEnabled = false;
  34507. };
  34508. SIMDHelper.EnableSIMD = function () {
  34509. if (window.SIMD === undefined) {
  34510. return;
  34511. }
  34512. // Replace functions
  34513. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34514. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34515. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34516. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34517. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34518. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34519. get: function () { return this._data[0]; },
  34520. set: function (value) {
  34521. if (!this._data) {
  34522. this._data = new Float32Array(3);
  34523. }
  34524. this._data[0] = value;
  34525. }
  34526. });
  34527. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34528. get: function () { return this._data[1]; },
  34529. set: function (value) {
  34530. this._data[1] = value;
  34531. }
  34532. });
  34533. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34534. get: function () { return this._data[2]; },
  34535. set: function (value) {
  34536. this._data[2] = value;
  34537. }
  34538. });
  34539. SIMDHelper._isEnabled = true;
  34540. };
  34541. SIMDHelper._isEnabled = false;
  34542. return SIMDHelper;
  34543. })();
  34544. BABYLON.SIMDHelper = SIMDHelper;
  34545. })(BABYLON || (BABYLON = {}));
  34546. var BABYLON;
  34547. (function (BABYLON) {
  34548. /**
  34549. * This class describe a rectangle that were added to the map.
  34550. * You have access to its coordinates either in pixel or normalized (UV)
  34551. */
  34552. var PackedRect = (function () {
  34553. function PackedRect(root, parent, pos, size) {
  34554. this._pos = pos;
  34555. this._size = size;
  34556. this._root = root;
  34557. this._parent = parent;
  34558. }
  34559. Object.defineProperty(PackedRect.prototype, "pos", {
  34560. /**
  34561. * @returns the position of this node into the map
  34562. */
  34563. get: function () {
  34564. return this._pos;
  34565. },
  34566. enumerable: true,
  34567. configurable: true
  34568. });
  34569. Object.defineProperty(PackedRect.prototype, "contentSize", {
  34570. /**
  34571. * @returns the size of the rectangle this node handles
  34572. */
  34573. get: function () {
  34574. return this._contentSize;
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. Object.defineProperty(PackedRect.prototype, "UVs", {
  34580. /**
  34581. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  34582. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  34583. */
  34584. get: function () {
  34585. var mainWidth = this._root._size.width;
  34586. var mainHeight = this._root._size.height;
  34587. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  34588. var rightBottom = new BABYLON.Vector2((this._pos.x + this._contentSize.width - 1) / mainWidth, (this._pos.y + this._contentSize.height - 1) / mainHeight);
  34589. var uvs = new Array();
  34590. uvs.push(topLeft);
  34591. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  34592. uvs.push(rightBottom);
  34593. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  34594. return uvs;
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. /**
  34600. * Free this rectangle from the map.
  34601. * Call this method when you no longer need the rectangle to be in the map.
  34602. */
  34603. PackedRect.prototype.freeContent = function () {
  34604. if (!this.contentSize) {
  34605. return;
  34606. }
  34607. this._contentSize = null;
  34608. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  34609. this.attemptDefrag();
  34610. };
  34611. Object.defineProperty(PackedRect.prototype, "isUsed", {
  34612. get: function () {
  34613. return this._contentSize != null || this._leftNode != null;
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  34619. var node = this.findNode(contentSize);
  34620. // Not enought space...
  34621. if (!node) {
  34622. return null;
  34623. }
  34624. node.splitNode(contentSize);
  34625. return node;
  34626. };
  34627. PackedRect.prototype.findNode = function (size) {
  34628. var resNode = null;
  34629. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  34630. if (this.isUsed) {
  34631. if (this._leftNode) {
  34632. resNode = this._leftNode.findNode(size);
  34633. }
  34634. if (!resNode && this._rightNode) {
  34635. resNode = this._rightNode.findNode(size);
  34636. }
  34637. if (!resNode && this._bottomNode) {
  34638. resNode = this._bottomNode.findNode(size);
  34639. }
  34640. }
  34641. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  34642. resNode = this;
  34643. }
  34644. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  34645. resNode = this;
  34646. }
  34647. return resNode;
  34648. };
  34649. PackedRect.prototype.splitNode = function (contentSize) {
  34650. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  34651. if (!this._contentSize && this._initialSize) {
  34652. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  34653. return this._leftNode.splitNode(contentSize);
  34654. }
  34655. else {
  34656. this._contentSize = contentSize.clone();
  34657. this._initialSize = contentSize.clone();
  34658. if (contentSize.width !== this._size.width) {
  34659. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  34660. }
  34661. if (contentSize.height !== this._size.height) {
  34662. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  34663. }
  34664. return this;
  34665. }
  34666. };
  34667. PackedRect.prototype.attemptDefrag = function () {
  34668. if (!this.isUsed && this.isRecursiveFree) {
  34669. this.clearNode();
  34670. if (this._parent) {
  34671. this._parent.attemptDefrag();
  34672. }
  34673. }
  34674. };
  34675. PackedRect.prototype.clearNode = function () {
  34676. this._initialSize = null;
  34677. this._rightNode = null;
  34678. this._bottomNode = null;
  34679. };
  34680. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  34681. get: function () {
  34682. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. PackedRect.prototype.evalFreeSize = function (size) {
  34688. var levelSize = 0;
  34689. if (!this.isUsed) {
  34690. if (this._initialSize) {
  34691. levelSize = this._initialSize.surface;
  34692. }
  34693. else {
  34694. levelSize = this._size.surface;
  34695. }
  34696. }
  34697. if (this._rightNode) {
  34698. levelSize += this._rightNode.evalFreeSize(0);
  34699. }
  34700. if (this._bottomNode) {
  34701. levelSize += this._bottomNode.evalFreeSize(0);
  34702. }
  34703. return levelSize + size;
  34704. };
  34705. return PackedRect;
  34706. })();
  34707. BABYLON.PackedRect = PackedRect;
  34708. /**
  34709. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimaly as possible.
  34710. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  34711. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their lifecycle.
  34712. */
  34713. var RectPackingMap = (function (_super) {
  34714. __extends(RectPackingMap, _super);
  34715. /**
  34716. * Create an instance of the object with a dimension using the given size
  34717. * @param size The dimension of the rectangle that will contain all the sub ones.
  34718. */
  34719. function RectPackingMap(size) {
  34720. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  34721. this._root = this;
  34722. }
  34723. /**
  34724. * Add a rectangle, finding the best location to store it into the map
  34725. * @param size the dimension of the rectangle to store
  34726. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  34727. */
  34728. RectPackingMap.prototype.addRect = function (size) {
  34729. var node = this.findAndSplitNode(size);
  34730. return node;
  34731. };
  34732. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  34733. /**
  34734. * Return the current space free normalized between [0;1]
  34735. * @returns {}
  34736. */
  34737. get: function () {
  34738. var freeSize = 0;
  34739. freeSize = this.evalFreeSize(freeSize);
  34740. return freeSize / (this._size.width * this._size.height);
  34741. },
  34742. enumerable: true,
  34743. configurable: true
  34744. });
  34745. return RectPackingMap;
  34746. })(PackedRect);
  34747. BABYLON.RectPackingMap = RectPackingMap;
  34748. })(BABYLON || (BABYLON = {}));
  34749. var BABYLON;
  34750. (function (BABYLON) {
  34751. var DynamicFloatArrayElementInfo = (function () {
  34752. function DynamicFloatArrayElementInfo() {
  34753. }
  34754. return DynamicFloatArrayElementInfo;
  34755. })();
  34756. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  34757. /**
  34758. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  34759. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  34760. * It was first built to effiently maintain the WebGlBuffer that contain instancing based data.
  34761. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  34762. * Beware, calling pack() may change the offset of some Entries because this method will defrag the Float32Array to replace empty elements by moving allocated ones at their location.
  34763. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there're no "free holes".
  34764. */
  34765. var DynamicFloatArray = (function () {
  34766. /**
  34767. * Construct an instance of the dynamic float array
  34768. * @param stride size of one element in float (i.e. not bytes!)
  34769. * @param initialElementCount the number of available entries at construction
  34770. */
  34771. function DynamicFloatArray(stride, initialElementCount) {
  34772. this._stride = stride;
  34773. this.buffer = new Float32Array(stride * initialElementCount);
  34774. this._lastUsed = 0;
  34775. this._firstFree = 0;
  34776. this._allEntries = new Array(initialElementCount);
  34777. this._freeEntries = new Array(initialElementCount);
  34778. for (var i = 0; i < initialElementCount; i++) {
  34779. var element = new DynamicFloatArrayElementInfo();
  34780. element.offset = i * stride;
  34781. this._allEntries[i] = element;
  34782. this._freeEntries[initialElementCount - i - 1] = element;
  34783. }
  34784. }
  34785. /**
  34786. * Allocate an element in the array.
  34787. * @return the element info instance that contains the offset into the main buffer of the element's location.
  34788. * Beware, this offset may change when you call pack()
  34789. */
  34790. DynamicFloatArray.prototype.allocElement = function () {
  34791. if (this._freeEntries.length === 0) {
  34792. this._growBuffer();
  34793. }
  34794. var el = this._freeEntries.pop();
  34795. this._lastUsed = Math.max(el.offset, this._lastUsed);
  34796. if (el.offset === this._firstFree) {
  34797. if (this._freeEntries.length > 0) {
  34798. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  34799. }
  34800. else {
  34801. this._firstFree += this._stride;
  34802. }
  34803. }
  34804. return el;
  34805. };
  34806. /**
  34807. * Free the element corresponding to the given element info
  34808. * @param elInfo the element that describe the allocated element
  34809. */
  34810. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  34811. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  34812. this._freeEntries.push(elInfo);
  34813. };
  34814. /**
  34815. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  34816. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  34817. * @return the subarray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  34818. */
  34819. DynamicFloatArray.prototype.pack = function () {
  34820. // no free slot? no need to pack
  34821. if (this._freeEntries.length === 0) {
  34822. return this.buffer;
  34823. }
  34824. // If the buffer is already packed the last used will always be lower than the first free
  34825. if (this._lastUsed < this._firstFree) {
  34826. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  34827. return elementsBuffer_1;
  34828. }
  34829. var s = this._stride;
  34830. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  34831. var lastFree = new DynamicFloatArrayElementInfo();
  34832. lastFree.offset = this.totalElementCount * s;
  34833. this._freeEntries.push(lastFree);
  34834. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  34835. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  34836. var firstFreeSlotOffset = sortedFree[0].offset;
  34837. var freeZoneSize = 1;
  34838. // The sortedFree array is sorted in reverse, first free at the end, last free at the beginning, so we loop from the end to beginning
  34839. var prevOffset = sortedFree[0].offset;
  34840. for (var i = 1; i < sortedFree.length; i++) {
  34841. var curFree = sortedFree[i];
  34842. var curOffset = curFree.offset;
  34843. // Compute the distance between this offset and the previous
  34844. var distance = curOffset - prevOffset;
  34845. // If the distance is the stride size, they are adjacents, it good, move to the next
  34846. if (distance === s) {
  34847. // Free zone is one element bigger
  34848. ++freeZoneSize;
  34849. // as we're about to iterate to the next, the cur becomes the prev...
  34850. prevOffset = curOffset;
  34851. continue;
  34852. }
  34853. // Distance is bigger, which means there's x element between the previous free and this one
  34854. var usedRange = (distance / s) - 1;
  34855. // Two cases the free zone is smaller than the data to move or bigger
  34856. // Copy what can fit in the free zone
  34857. var curMoveOffset = curOffset - s;
  34858. var copyCount = Math.min(freeZoneSize, usedRange);
  34859. for (var j = 0; j < copyCount; j++) {
  34860. var freeI = firstFreeSlotOffset / s;
  34861. var curI = curMoveOffset / s;
  34862. var moveEl = sortedAll[curI];
  34863. this._moveElement(moveEl, firstFreeSlotOffset);
  34864. var replacedEl = sortedAll[freeI];
  34865. // set the offset of the element element we replace with a value that will make it discard at the end of the method
  34866. replacedEl.offset = curMoveOffset;
  34867. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  34868. sortedAll[freeI] = moveEl;
  34869. sortedAll[curI] = replacedEl;
  34870. curMoveOffset -= s;
  34871. firstFreeSlotOffset += s;
  34872. }
  34873. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  34874. if (freeZoneSize <= usedRange) {
  34875. firstFreeSlotOffset = curOffset;
  34876. freeZoneSize = 1;
  34877. }
  34878. else {
  34879. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  34880. }
  34881. // as we're about to iterate to the next, the cur becomes the prev...
  34882. prevOffset = curOffset;
  34883. }
  34884. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  34885. this._lastUsed = firstFreeSlotOffset - s;
  34886. this._firstFree = firstFreeSlotOffset;
  34887. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  34888. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  34889. this._allEntries = sortedAll;
  34890. return elementsBuffer;
  34891. };
  34892. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  34893. for (var i = 0; i < this._stride; i++) {
  34894. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  34895. }
  34896. element.offset = destOffset;
  34897. };
  34898. DynamicFloatArray.prototype._growBuffer = function () {
  34899. // Allocate the new buffer with 50% more entries, copy the content of the current one
  34900. var newElCount = this.totalElementCount * 1.5;
  34901. var newBuffer = new Float32Array(newElCount * this._stride);
  34902. newBuffer.set(this.buffer);
  34903. var addedCount = newElCount - this.totalElementCount;
  34904. this._allEntries.length += addedCount;
  34905. this._freeEntries.length += addedCount;
  34906. for (var i = this.totalElementCount; i < newElCount; i++) {
  34907. var el = new DynamicFloatArrayElementInfo();
  34908. el.offset = i * this._stride;
  34909. this._allEntries[i] = el;
  34910. this._freeEntries[i] = el;
  34911. }
  34912. this.buffer = newBuffer;
  34913. this.totalElementCount = newElCount;
  34914. };
  34915. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  34916. /**
  34917. * Get the total count of entries that can fit in the current buffer
  34918. * @returns the elements count
  34919. */
  34920. get: function () {
  34921. return this._allEntries.length;
  34922. },
  34923. enumerable: true,
  34924. configurable: true
  34925. });
  34926. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  34927. /**
  34928. * Get the count of free entries that can still be allocated without resizing the buffer
  34929. * @returns the free elements count
  34930. */
  34931. get: function () {
  34932. return this._freeEntries.length;
  34933. },
  34934. enumerable: true,
  34935. configurable: true
  34936. });
  34937. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  34938. /**
  34939. * Get the count of allocated elements
  34940. * @returns the allocated elements count
  34941. */
  34942. get: function () {
  34943. return this._allEntries.length - this._freeEntries.length;
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  34949. /**
  34950. * Return the size of one element in float
  34951. * @returns the size in float
  34952. */
  34953. get: function () {
  34954. return this._stride;
  34955. },
  34956. enumerable: true,
  34957. configurable: true
  34958. });
  34959. return DynamicFloatArray;
  34960. })();
  34961. BABYLON.DynamicFloatArray = DynamicFloatArray;
  34962. })(BABYLON || (BABYLON = {}));
  34963. var BABYLON;
  34964. (function (BABYLON) {
  34965. var ShaderMaterial = (function (_super) {
  34966. __extends(ShaderMaterial, _super);
  34967. function ShaderMaterial(name, scene, shaderPath, options) {
  34968. _super.call(this, name, scene);
  34969. this._textures = {};
  34970. this._floats = {};
  34971. this._floatsArrays = {};
  34972. this._colors3 = {};
  34973. this._colors4 = {};
  34974. this._vectors2 = {};
  34975. this._vectors3 = {};
  34976. this._vectors4 = {};
  34977. this._matrices = {};
  34978. this._matrices3x3 = {};
  34979. this._matrices2x2 = {};
  34980. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  34981. this._shaderPath = shaderPath;
  34982. options.needAlphaBlending = options.needAlphaBlending || false;
  34983. options.needAlphaTesting = options.needAlphaTesting || false;
  34984. options.attributes = options.attributes || ["position", "normal", "uv"];
  34985. options.uniforms = options.uniforms || ["worldViewProjection"];
  34986. options.samplers = options.samplers || [];
  34987. options.defines = options.defines || [];
  34988. this._options = options;
  34989. }
  34990. ShaderMaterial.prototype.needAlphaBlending = function () {
  34991. return this._options.needAlphaBlending;
  34992. };
  34993. ShaderMaterial.prototype.needAlphaTesting = function () {
  34994. return this._options.needAlphaTesting;
  34995. };
  34996. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  34997. if (this._options.uniforms.indexOf(uniformName) === -1) {
  34998. this._options.uniforms.push(uniformName);
  34999. }
  35000. };
  35001. ShaderMaterial.prototype.setTexture = function (name, texture) {
  35002. if (this._options.samplers.indexOf(name) === -1) {
  35003. this._options.samplers.push(name);
  35004. }
  35005. this._textures[name] = texture;
  35006. return this;
  35007. };
  35008. ShaderMaterial.prototype.setFloat = function (name, value) {
  35009. this._checkUniform(name);
  35010. this._floats[name] = value;
  35011. return this;
  35012. };
  35013. ShaderMaterial.prototype.setFloats = function (name, value) {
  35014. this._checkUniform(name);
  35015. this._floatsArrays[name] = value;
  35016. return this;
  35017. };
  35018. ShaderMaterial.prototype.setColor3 = function (name, value) {
  35019. this._checkUniform(name);
  35020. this._colors3[name] = value;
  35021. return this;
  35022. };
  35023. ShaderMaterial.prototype.setColor4 = function (name, value) {
  35024. this._checkUniform(name);
  35025. this._colors4[name] = value;
  35026. return this;
  35027. };
  35028. ShaderMaterial.prototype.setVector2 = function (name, value) {
  35029. this._checkUniform(name);
  35030. this._vectors2[name] = value;
  35031. return this;
  35032. };
  35033. ShaderMaterial.prototype.setVector3 = function (name, value) {
  35034. this._checkUniform(name);
  35035. this._vectors3[name] = value;
  35036. return this;
  35037. };
  35038. ShaderMaterial.prototype.setVector4 = function (name, value) {
  35039. this._checkUniform(name);
  35040. this._vectors4[name] = value;
  35041. return this;
  35042. };
  35043. ShaderMaterial.prototype.setMatrix = function (name, value) {
  35044. this._checkUniform(name);
  35045. this._matrices[name] = value;
  35046. return this;
  35047. };
  35048. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  35049. this._checkUniform(name);
  35050. this._matrices3x3[name] = value;
  35051. return this;
  35052. };
  35053. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  35054. this._checkUniform(name);
  35055. this._matrices2x2[name] = value;
  35056. return this;
  35057. };
  35058. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  35059. var scene = this.getScene();
  35060. var engine = scene.getEngine();
  35061. if (!this.checkReadyOnEveryCall) {
  35062. if (this._renderId === scene.getRenderId()) {
  35063. return true;
  35064. }
  35065. }
  35066. // Instances
  35067. var defines = [];
  35068. var fallbacks = new BABYLON.EffectFallbacks();
  35069. if (useInstances) {
  35070. defines.push("#define INSTANCES");
  35071. }
  35072. for (var index = 0; index < this._options.defines.length; index++) {
  35073. defines.push(this._options.defines[index]);
  35074. }
  35075. // Bones
  35076. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35077. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  35078. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  35079. fallbacks.addCPUSkinningFallback(0, mesh);
  35080. }
  35081. // Alpha test
  35082. if (engine.getAlphaTesting()) {
  35083. defines.push("#define ALPHATEST");
  35084. }
  35085. var previousEffect = this._effect;
  35086. var join = defines.join("\n");
  35087. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  35088. if (!this._effect.isReady()) {
  35089. return false;
  35090. }
  35091. if (previousEffect !== this._effect) {
  35092. scene.resetCachedMaterial();
  35093. }
  35094. this._renderId = scene.getRenderId();
  35095. return true;
  35096. };
  35097. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35098. var scene = this.getScene();
  35099. if (this._options.uniforms.indexOf("world") !== -1) {
  35100. this._effect.setMatrix("world", world);
  35101. }
  35102. if (this._options.uniforms.indexOf("worldView") !== -1) {
  35103. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  35104. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  35105. }
  35106. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  35107. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  35108. }
  35109. };
  35110. ShaderMaterial.prototype.bind = function (world, mesh) {
  35111. // Std values
  35112. this.bindOnlyWorldMatrix(world);
  35113. if (this.getScene().getCachedMaterial() !== this) {
  35114. if (this._options.uniforms.indexOf("view") !== -1) {
  35115. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  35116. }
  35117. if (this._options.uniforms.indexOf("projection") !== -1) {
  35118. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  35119. }
  35120. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  35121. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35122. }
  35123. // Bones
  35124. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  35125. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  35126. }
  35127. // Texture
  35128. for (var name in this._textures) {
  35129. this._effect.setTexture(name, this._textures[name]);
  35130. }
  35131. // Float
  35132. for (name in this._floats) {
  35133. this._effect.setFloat(name, this._floats[name]);
  35134. }
  35135. // Float s
  35136. for (name in this._floatsArrays) {
  35137. this._effect.setArray(name, this._floatsArrays[name]);
  35138. }
  35139. // Color3
  35140. for (name in this._colors3) {
  35141. this._effect.setColor3(name, this._colors3[name]);
  35142. }
  35143. // Color4
  35144. for (name in this._colors4) {
  35145. var color = this._colors4[name];
  35146. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  35147. }
  35148. // Vector2
  35149. for (name in this._vectors2) {
  35150. this._effect.setVector2(name, this._vectors2[name]);
  35151. }
  35152. // Vector3
  35153. for (name in this._vectors3) {
  35154. this._effect.setVector3(name, this._vectors3[name]);
  35155. }
  35156. // Vector4
  35157. for (name in this._vectors4) {
  35158. this._effect.setVector4(name, this._vectors4[name]);
  35159. }
  35160. // Matrix
  35161. for (name in this._matrices) {
  35162. this._effect.setMatrix(name, this._matrices[name]);
  35163. }
  35164. // Matrix 3x3
  35165. for (name in this._matrices3x3) {
  35166. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  35167. }
  35168. // Matrix 2x2
  35169. for (name in this._matrices2x2) {
  35170. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  35171. }
  35172. }
  35173. _super.prototype.bind.call(this, world, mesh);
  35174. };
  35175. ShaderMaterial.prototype.clone = function (name) {
  35176. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  35177. return newShaderMaterial;
  35178. };
  35179. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35180. if (forceDisposeTextures) {
  35181. for (var name in this._textures) {
  35182. this._textures[name].dispose();
  35183. }
  35184. }
  35185. this._textures = {};
  35186. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35187. };
  35188. ShaderMaterial.prototype.serialize = function () {
  35189. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35190. serializationObject.customType = "BABYLON.ShaderMaterial";
  35191. serializationObject.options = this._options;
  35192. serializationObject.shaderPath = this._shaderPath;
  35193. // Texture
  35194. serializationObject.textures = {};
  35195. for (var name in this._textures) {
  35196. serializationObject.textures[name] = this._textures[name].serialize();
  35197. }
  35198. // Float
  35199. serializationObject.floats = {};
  35200. for (name in this._floats) {
  35201. serializationObject.floats[name] = this._floats[name];
  35202. }
  35203. // Float s
  35204. serializationObject.floatArrays = {};
  35205. for (name in this._floatsArrays) {
  35206. serializationObject.floatArrays[name] = this._floatsArrays[name];
  35207. }
  35208. // Color3
  35209. serializationObject.colors3 = {};
  35210. for (name in this._colors3) {
  35211. serializationObject.colors3[name] = this._colors3[name].asArray();
  35212. }
  35213. // Color4
  35214. serializationObject.colors4 = {};
  35215. for (name in this._colors4) {
  35216. serializationObject.colors4[name] = this._colors4[name].asArray();
  35217. }
  35218. // Vector2
  35219. serializationObject.vectors2 = {};
  35220. for (name in this._vectors2) {
  35221. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  35222. }
  35223. // Vector3
  35224. serializationObject.vectors3 = {};
  35225. for (name in this._vectors3) {
  35226. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  35227. }
  35228. // Vector4
  35229. serializationObject.vectors4 = {};
  35230. for (name in this._vectors4) {
  35231. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  35232. }
  35233. // Matrix
  35234. serializationObject.matrices = {};
  35235. for (name in this._matrices) {
  35236. serializationObject.matrices[name] = this._matrices[name].asArray();
  35237. }
  35238. // Matrix 3x3
  35239. serializationObject.matrices3x3 = {};
  35240. for (name in this._matrices3x3) {
  35241. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  35242. }
  35243. // Matrix 2x2
  35244. serializationObject.matrices2x2 = {};
  35245. for (name in this._matrices2x2) {
  35246. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  35247. }
  35248. return serializationObject;
  35249. };
  35250. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  35251. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  35252. // Texture
  35253. for (var name in source.textures) {
  35254. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  35255. }
  35256. // Float
  35257. for (name in source.floats) {
  35258. material.setFloat(name, source.floats[name]);
  35259. }
  35260. // Float s
  35261. for (name in source.floatsArrays) {
  35262. material.setFloats(name, source.floatsArrays[name]);
  35263. }
  35264. // Color3
  35265. for (name in source.colors3) {
  35266. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  35267. }
  35268. // Color4
  35269. for (name in source.colors4) {
  35270. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  35271. }
  35272. // Vector2
  35273. for (name in source.vectors2) {
  35274. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  35275. }
  35276. // Vector3
  35277. for (name in source.vectors3) {
  35278. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  35279. }
  35280. // Vector4
  35281. for (name in source.vectors4) {
  35282. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  35283. }
  35284. // Matrix
  35285. for (name in source.matrices) {
  35286. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  35287. }
  35288. // Matrix 3x3
  35289. for (name in source.matrices3x3) {
  35290. material.setMatrix3x3(name, source.matrices3x3[name]);
  35291. }
  35292. // Matrix 2x2
  35293. for (name in source.matrices2x2) {
  35294. material.setMatrix2x2(name, source.matrices2x2[name]);
  35295. }
  35296. return material;
  35297. };
  35298. return ShaderMaterial;
  35299. })(BABYLON.Material);
  35300. BABYLON.ShaderMaterial = ShaderMaterial;
  35301. })(BABYLON || (BABYLON = {}));
  35302. var BABYLON;
  35303. (function (BABYLON) {
  35304. var Internals;
  35305. (function (Internals) {
  35306. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  35307. // All values and structures referenced from:
  35308. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  35309. var DDS_MAGIC = 0x20534444;
  35310. 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;
  35311. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  35312. 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;
  35313. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  35314. function FourCCToInt32(value) {
  35315. return value.charCodeAt(0) +
  35316. (value.charCodeAt(1) << 8) +
  35317. (value.charCodeAt(2) << 16) +
  35318. (value.charCodeAt(3) << 24);
  35319. }
  35320. function Int32ToFourCC(value) {
  35321. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  35322. }
  35323. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  35324. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  35325. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  35326. var headerLengthInt = 31; // The header length in 32 bit ints
  35327. // Offsets into the header array
  35328. var off_magic = 0;
  35329. var off_size = 1;
  35330. var off_flags = 2;
  35331. var off_height = 3;
  35332. var off_width = 4;
  35333. var off_mipmapCount = 7;
  35334. var off_pfFlags = 20;
  35335. var off_pfFourCC = 21;
  35336. var off_RGBbpp = 22;
  35337. var off_RMask = 23;
  35338. var off_GMask = 24;
  35339. var off_BMask = 25;
  35340. var off_AMask = 26;
  35341. var off_caps1 = 27;
  35342. var off_caps2 = 28;
  35343. ;
  35344. var DDSTools = (function () {
  35345. function DDSTools() {
  35346. }
  35347. DDSTools.GetDDSInfo = function (arrayBuffer) {
  35348. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  35349. var mipmapCount = 1;
  35350. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  35351. mipmapCount = Math.max(1, header[off_mipmapCount]);
  35352. }
  35353. return {
  35354. width: header[off_width],
  35355. height: header[off_height],
  35356. mipmapCount: mipmapCount,
  35357. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  35358. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  35359. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  35360. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  35361. };
  35362. };
  35363. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  35364. var byteArray = new Uint8Array(dataLength);
  35365. var srcData = new Uint8Array(arrayBuffer);
  35366. var index = 0;
  35367. for (var y = height - 1; y >= 0; y--) {
  35368. for (var x = 0; x < width; x++) {
  35369. var srcPos = dataOffset + (x + y * width) * 4;
  35370. byteArray[index + 2] = srcData[srcPos];
  35371. byteArray[index + 1] = srcData[srcPos + 1];
  35372. byteArray[index] = srcData[srcPos + 2];
  35373. byteArray[index + 3] = srcData[srcPos + 3];
  35374. index += 4;
  35375. }
  35376. }
  35377. return byteArray;
  35378. };
  35379. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  35380. var byteArray = new Uint8Array(dataLength);
  35381. var srcData = new Uint8Array(arrayBuffer);
  35382. var index = 0;
  35383. for (var y = height - 1; y >= 0; y--) {
  35384. for (var x = 0; x < width; x++) {
  35385. var srcPos = dataOffset + (x + y * width) * 3;
  35386. byteArray[index + 2] = srcData[srcPos];
  35387. byteArray[index + 1] = srcData[srcPos + 1];
  35388. byteArray[index] = srcData[srcPos + 2];
  35389. index += 3;
  35390. }
  35391. }
  35392. return byteArray;
  35393. };
  35394. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  35395. var byteArray = new Uint8Array(dataLength);
  35396. var srcData = new Uint8Array(arrayBuffer);
  35397. var index = 0;
  35398. for (var y = height - 1; y >= 0; y--) {
  35399. for (var x = 0; x < width; x++) {
  35400. var srcPos = dataOffset + (x + y * width);
  35401. byteArray[index] = srcData[srcPos];
  35402. index++;
  35403. }
  35404. }
  35405. return byteArray;
  35406. };
  35407. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  35408. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  35409. if (header[off_magic] != DDS_MAGIC) {
  35410. BABYLON.Tools.Error("Invalid magic number in DDS header");
  35411. return;
  35412. }
  35413. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  35414. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  35415. return;
  35416. }
  35417. if (info.isFourCC) {
  35418. fourCC = header[off_pfFourCC];
  35419. switch (fourCC) {
  35420. case FOURCC_DXT1:
  35421. blockBytes = 8;
  35422. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  35423. break;
  35424. case FOURCC_DXT3:
  35425. blockBytes = 16;
  35426. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  35427. break;
  35428. case FOURCC_DXT5:
  35429. blockBytes = 16;
  35430. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  35431. break;
  35432. default:
  35433. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  35434. return;
  35435. }
  35436. }
  35437. mipmapCount = 1;
  35438. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  35439. mipmapCount = Math.max(1, header[off_mipmapCount]);
  35440. }
  35441. var bpp = header[off_RGBbpp];
  35442. for (var face = 0; face < faces; face++) {
  35443. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  35444. width = header[off_width];
  35445. height = header[off_height];
  35446. dataOffset = header[off_size] + 4;
  35447. for (i = 0; i < mipmapCount; ++i) {
  35448. if (info.isRGB) {
  35449. if (bpp === 24) {
  35450. dataLength = width * height * 3;
  35451. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  35452. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  35453. }
  35454. else {
  35455. dataLength = width * height * 4;
  35456. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  35457. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  35458. }
  35459. }
  35460. else if (info.isLuminance) {
  35461. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  35462. var unpaddedRowSize = width;
  35463. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  35464. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  35465. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  35466. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  35467. }
  35468. else {
  35469. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  35470. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  35471. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  35472. }
  35473. dataOffset += dataLength;
  35474. width *= 0.5;
  35475. height *= 0.5;
  35476. width = Math.max(1.0, width);
  35477. height = Math.max(1.0, height);
  35478. }
  35479. }
  35480. };
  35481. return DDSTools;
  35482. })();
  35483. Internals.DDSTools = DDSTools;
  35484. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35485. })(BABYLON || (BABYLON = {}));
  35486. var BABYLON;
  35487. (function (BABYLON) {
  35488. var CannonJSPlugin = (function () {
  35489. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  35490. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  35491. if (iterations === void 0) { iterations = 10; }
  35492. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  35493. this.name = "CannonJSPlugin";
  35494. this._physicsMaterials = [];
  35495. this._fixedTimeStep = 1 / 60;
  35496. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  35497. this._currentCollisionGroup = 2;
  35498. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  35499. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  35500. this._tmpPosition = BABYLON.Vector3.Zero();
  35501. this._tmpQuaternion = new BABYLON.Quaternion();
  35502. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  35503. this._tmpDeltaRotation = new BABYLON.Quaternion();
  35504. this._tmpUnityRotation = new BABYLON.Quaternion();
  35505. if (!this.isSupported()) {
  35506. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  35507. return;
  35508. }
  35509. this.world = new CANNON.World();
  35510. this.world.broadphase = new CANNON.NaiveBroadphase();
  35511. this.world.solver.iterations = iterations;
  35512. }
  35513. CannonJSPlugin.prototype.setGravity = function (gravity) {
  35514. this.world.gravity.copy(gravity);
  35515. };
  35516. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  35517. this._fixedTimeStep = timeStep;
  35518. };
  35519. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  35520. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  35521. };
  35522. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  35523. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  35524. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  35525. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  35526. };
  35527. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  35528. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  35529. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  35530. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  35531. };
  35532. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  35533. //parent-child relationship. Does this impostor has a parent impostor?
  35534. if (impostor.parent) {
  35535. if (impostor.physicsBody) {
  35536. this.removePhysicsBody(impostor);
  35537. //TODO is that needed?
  35538. impostor.forceUpdate();
  35539. }
  35540. return;
  35541. }
  35542. //should a new body be created for this impostor?
  35543. if (impostor.isBodyInitRequired()) {
  35544. var shape = this._createShape(impostor);
  35545. //unregister events, if body is being changed
  35546. var oldBody = impostor.physicsBody;
  35547. if (oldBody) {
  35548. this.removePhysicsBody(impostor);
  35549. }
  35550. //create the body and material
  35551. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  35552. var bodyCreationObject = {
  35553. mass: impostor.getParam("mass"),
  35554. material: material
  35555. };
  35556. // A simple extend, in case native options were used.
  35557. var nativeOptions = impostor.getParam("nativeOptions");
  35558. for (var key in nativeOptions) {
  35559. if (nativeOptions.hasOwnProperty(key)) {
  35560. bodyCreationObject[key] = nativeOptions[key];
  35561. }
  35562. }
  35563. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  35564. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  35565. this.world.addEventListener("preStep", impostor.beforeStep);
  35566. this.world.addEventListener("postStep", impostor.afterStep);
  35567. impostor.physicsBody.addShape(shape);
  35568. this.world.add(impostor.physicsBody);
  35569. //try to keep the body moving in the right direction by taking old properties.
  35570. //Should be tested!
  35571. if (oldBody) {
  35572. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  35573. impostor.physicsBody[param].copy(oldBody[param]);
  35574. });
  35575. }
  35576. this._processChildMeshes(impostor);
  35577. }
  35578. //now update the body's transformation
  35579. this._updatePhysicsBodyTransformation(impostor);
  35580. };
  35581. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  35582. var _this = this;
  35583. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  35584. if (meshChildren.length) {
  35585. var processMesh = function (localPosition, mesh) {
  35586. var childImpostor = mesh.getPhysicsImpostor();
  35587. if (childImpostor) {
  35588. var parent = childImpostor.parent;
  35589. if (parent !== mainImpostor) {
  35590. var localPosition = mesh.position;
  35591. if (childImpostor.physicsBody) {
  35592. _this.removePhysicsBody(childImpostor);
  35593. childImpostor.physicsBody = null;
  35594. }
  35595. childImpostor.parent = mainImpostor;
  35596. childImpostor.resetUpdateFlags();
  35597. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  35598. //Add the mass of the children.
  35599. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  35600. }
  35601. }
  35602. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  35603. };
  35604. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  35605. }
  35606. };
  35607. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35608. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  35609. this.world.removeEventListener("preStep", impostor.beforeStep);
  35610. this.world.removeEventListener("postStep", impostor.afterStep);
  35611. this.world.remove(impostor.physicsBody);
  35612. };
  35613. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35614. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35615. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35616. if (!mainBody || !connectedBody) {
  35617. return;
  35618. }
  35619. var constraint;
  35620. var jointData = impostorJoint.joint.jointData;
  35621. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  35622. var constraintData = {
  35623. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  35624. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  35625. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  35626. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  35627. maxForce: jointData.nativeParams.maxForce,
  35628. collideConnected: !!jointData.collision
  35629. };
  35630. //Not needed, Cannon has a collideConnected flag
  35631. /*if (!jointData.collision) {
  35632. //add 1st body to a collision group of its own, if it is not in 1
  35633. if (mainBody.collisionFilterGroup === 1) {
  35634. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  35635. this._currentCollisionGroup <<= 1;
  35636. }
  35637. if (connectedBody.collisionFilterGroup === 1) {
  35638. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  35639. this._currentCollisionGroup <<= 1;
  35640. }
  35641. //add their mask to the collisionFilterMask of each other:
  35642. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  35643. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  35644. }*/
  35645. switch (impostorJoint.joint.type) {
  35646. case BABYLON.PhysicsJoint.HingeJoint:
  35647. case BABYLON.PhysicsJoint.Hinge2Joint:
  35648. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  35649. break;
  35650. case BABYLON.PhysicsJoint.DistanceJoint:
  35651. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  35652. break;
  35653. case BABYLON.PhysicsJoint.SpringJoint:
  35654. var springData = jointData;
  35655. constraint = new CANNON.Spring(mainBody, connectedBody, {
  35656. restLength: springData.length,
  35657. stiffness: springData.stiffness,
  35658. damping: springData.damping,
  35659. localAnchorA: constraintData.pivotA,
  35660. localAnchorB: constraintData.pivotB
  35661. });
  35662. break;
  35663. case BABYLON.PhysicsJoint.PointToPointJoint:
  35664. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35665. default:
  35666. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  35667. break;
  35668. }
  35669. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  35670. constraint.collideConnected = !!jointData.collision;
  35671. impostorJoint.joint.physicsJoint = constraint;
  35672. //don't add spring as constraint, as it is not one.
  35673. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  35674. this.world.addConstraint(constraint);
  35675. }
  35676. else {
  35677. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  35678. constraint.applyForce();
  35679. });
  35680. }
  35681. };
  35682. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  35683. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  35684. };
  35685. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  35686. var index;
  35687. var mat;
  35688. for (index = 0; index < this._physicsMaterials.length; index++) {
  35689. mat = this._physicsMaterials[index];
  35690. if (mat.friction === friction && mat.restitution === restitution) {
  35691. return mat;
  35692. }
  35693. }
  35694. var currentMat = new CANNON.Material(name);
  35695. currentMat.friction = friction;
  35696. currentMat.restitution = restitution;
  35697. this._physicsMaterials.push(currentMat);
  35698. return currentMat;
  35699. };
  35700. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  35701. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  35702. };
  35703. CannonJSPlugin.prototype._createShape = function (impostor) {
  35704. var object = impostor.object;
  35705. var returnValue;
  35706. var extendSize = impostor.getObjectExtendSize();
  35707. switch (impostor.type) {
  35708. case BABYLON.PhysicsEngine.SphereImpostor:
  35709. var radiusX = extendSize.x;
  35710. var radiusY = extendSize.y;
  35711. var radiusZ = extendSize.z;
  35712. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  35713. break;
  35714. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  35715. case BABYLON.PhysicsImpostor.CylinderImpostor:
  35716. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  35717. break;
  35718. case BABYLON.PhysicsImpostor.BoxImpostor:
  35719. var box = extendSize.scale(0.5);
  35720. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  35721. break;
  35722. case BABYLON.PhysicsImpostor.PlaneImpostor:
  35723. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  35724. returnValue = new CANNON.Plane();
  35725. break;
  35726. case BABYLON.PhysicsImpostor.MeshImpostor:
  35727. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  35728. var rawFaces = object.getIndices ? object.getIndices() : [];
  35729. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  35730. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  35731. break;
  35732. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  35733. returnValue = this._createHeightmap(object);
  35734. break;
  35735. case BABYLON.PhysicsImpostor.ParticleImpostor:
  35736. returnValue = new CANNON.Particle();
  35737. break;
  35738. }
  35739. return returnValue;
  35740. };
  35741. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  35742. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35743. var matrix = [];
  35744. //For now pointDepth will not be used and will be automatically calculated.
  35745. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  35746. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  35747. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  35748. var elementSize = dim * 2 / arraySize;
  35749. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  35750. for (var i = 0; i < pos.length; i = i + 3) {
  35751. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  35752. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  35753. var y = pos[i + 1] + minY;
  35754. if (!matrix[x]) {
  35755. matrix[x] = [];
  35756. }
  35757. if (!matrix[x][z]) {
  35758. matrix[x][z] = y;
  35759. }
  35760. matrix[x][z] = Math.max(y, matrix[x][z]);
  35761. }
  35762. for (var x = 0; x <= arraySize; ++x) {
  35763. if (!matrix[x]) {
  35764. var loc = 1;
  35765. while (!matrix[(x + loc) % arraySize]) {
  35766. loc++;
  35767. }
  35768. matrix[x] = matrix[(x + loc) % arraySize].slice();
  35769. }
  35770. for (var z = 0; z <= arraySize; ++z) {
  35771. if (!matrix[x][z]) {
  35772. var loc = 1;
  35773. var newValue;
  35774. while (newValue === undefined) {
  35775. newValue = matrix[x][(z + loc++) % arraySize];
  35776. }
  35777. matrix[x][z] = newValue;
  35778. }
  35779. }
  35780. }
  35781. var shape = new CANNON.Heightfield(matrix, {
  35782. elementSize: elementSize
  35783. });
  35784. //For future reference, needed for body transformation
  35785. shape.minY = minY;
  35786. return shape;
  35787. };
  35788. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  35789. var object = impostor.object;
  35790. //make sure it is updated...
  35791. object.computeWorldMatrix && object.computeWorldMatrix(true);
  35792. // The delta between the mesh position and the mesh bounding box center
  35793. var center = impostor.getObjectCenter();
  35794. var extendSize = impostor.getObjectExtendSize();
  35795. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  35796. this._tmpPosition.copyFrom(center);
  35797. var quaternion = object.rotationQuaternion;
  35798. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  35799. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  35800. //-90 DEG in X, precalculated
  35801. quaternion = quaternion.multiply(this._minus90X);
  35802. //Invert! (Precalculated, 90 deg in X)
  35803. //No need to clone. this will never change.
  35804. impostor.setDeltaRotation(this._plus90X);
  35805. }
  35806. //If it is a heightfield, if should be centered.
  35807. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  35808. var mesh = object;
  35809. //calculate the correct body position:
  35810. var rotationQuaternion = mesh.rotationQuaternion;
  35811. mesh.rotationQuaternion = this._tmpUnityRotation;
  35812. mesh.computeWorldMatrix(true);
  35813. //get original center with no rotation
  35814. var c = center.clone();
  35815. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  35816. //rotation is back
  35817. mesh.rotationQuaternion = rotationQuaternion;
  35818. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  35819. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  35820. mesh.setPivotMatrix(p);
  35821. mesh.computeWorldMatrix(true);
  35822. //calculate the translation
  35823. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  35824. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  35825. //add it inverted to the delta
  35826. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  35827. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  35828. mesh.setPivotMatrix(oldPivot);
  35829. mesh.computeWorldMatrix(true);
  35830. }
  35831. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  35832. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  35833. this._tmpPosition.copyFrom(object.position);
  35834. }
  35835. impostor.setDeltaPosition(this._tmpDeltaPosition);
  35836. //Now update the impostor object
  35837. impostor.physicsBody.position.copy(this._tmpPosition);
  35838. impostor.physicsBody.quaternion.copy(quaternion);
  35839. };
  35840. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35841. impostor.object.position.copyFrom(impostor.physicsBody.position);
  35842. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  35843. };
  35844. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35845. impostor.physicsBody.position.copy(newPosition);
  35846. impostor.physicsBody.quaternion.copy(newRotation);
  35847. };
  35848. CannonJSPlugin.prototype.isSupported = function () {
  35849. return window.CANNON !== undefined;
  35850. };
  35851. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35852. impostor.physicsBody.velocity.copy(velocity);
  35853. };
  35854. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35855. impostor.physicsBody.angularVelocity.copy(velocity);
  35856. };
  35857. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35858. var v = impostor.physicsBody.velocity;
  35859. if (!v)
  35860. return null;
  35861. return new BABYLON.Vector3(v.x, v.y, v.z);
  35862. };
  35863. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35864. var v = impostor.physicsBody.angularVelocity;
  35865. if (!v)
  35866. return null;
  35867. return new BABYLON.Vector3(v.x, v.y, v.z);
  35868. };
  35869. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35870. impostor.physicsBody.mass = mass;
  35871. impostor.physicsBody.updateMassProperties();
  35872. };
  35873. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  35874. impostor.physicsBody.sleep();
  35875. };
  35876. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  35877. impostor.physicsBody.wakeUp();
  35878. };
  35879. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35880. joint.physicsJoint.distance = maxDistance;
  35881. };
  35882. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  35883. if (!motorIndex) {
  35884. joint.physicsJoint.enableMotor();
  35885. }
  35886. };
  35887. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  35888. if (!motorIndex) {
  35889. joint.physicsJoint.disableMotor();
  35890. }
  35891. };
  35892. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35893. if (!motorIndex) {
  35894. joint.physicsJoint.enableMotor();
  35895. joint.physicsJoint.setMotorSpeed(speed);
  35896. if (maxForce) {
  35897. this.setLimit(joint, maxForce);
  35898. }
  35899. }
  35900. };
  35901. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  35902. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  35903. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  35904. };
  35905. CannonJSPlugin.prototype.dispose = function () {
  35906. //nothing to do, actually.
  35907. };
  35908. return CannonJSPlugin;
  35909. })();
  35910. BABYLON.CannonJSPlugin = CannonJSPlugin;
  35911. })(BABYLON || (BABYLON = {}));
  35912. var BABYLON;
  35913. (function (BABYLON) {
  35914. var OimoJSPlugin = (function () {
  35915. function OimoJSPlugin(iterations) {
  35916. this.name = "OimoJSPlugin";
  35917. this._tmpImpostorsArray = [];
  35918. this._tmpPositionVector = BABYLON.Vector3.Zero();
  35919. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  35920. this.world.clear();
  35921. //making sure no stats are calculated
  35922. this.world.isNoStat = true;
  35923. }
  35924. OimoJSPlugin.prototype.setGravity = function (gravity) {
  35925. this.world.gravity.copy(gravity);
  35926. };
  35927. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  35928. this.world.timeStep = timeStep;
  35929. };
  35930. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  35931. var _this = this;
  35932. impostors.forEach(function (impostor) {
  35933. impostor.beforeStep();
  35934. });
  35935. this.world.step();
  35936. impostors.forEach(function (impostor) {
  35937. impostor.afterStep();
  35938. //update the ordered impostors array
  35939. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  35940. });
  35941. //check for collisions
  35942. var contact = this.world.contacts;
  35943. while (contact !== null) {
  35944. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  35945. contact = contact.next;
  35946. continue;
  35947. }
  35948. //is this body colliding with any other? get the impostor
  35949. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  35950. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  35951. if (!mainImpostor || !collidingImpostor) {
  35952. contact = contact.next;
  35953. continue;
  35954. }
  35955. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  35956. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  35957. contact = contact.next;
  35958. }
  35959. };
  35960. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  35961. var mass = impostor.physicsBody.massInfo.mass;
  35962. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  35963. };
  35964. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  35965. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  35966. this.applyImpulse(impostor, force, contactPoint);
  35967. };
  35968. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  35969. var _this = this;
  35970. //parent-child relationship. Does this impostor has a parent impostor?
  35971. if (impostor.parent) {
  35972. if (impostor.physicsBody) {
  35973. this.removePhysicsBody(impostor);
  35974. //TODO is that needed?
  35975. impostor.forceUpdate();
  35976. }
  35977. return;
  35978. }
  35979. if (impostor.isBodyInitRequired()) {
  35980. var bodyConfig = {
  35981. name: impostor.uniqueId,
  35982. //Oimo must have mass, also for static objects.
  35983. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  35984. size: [],
  35985. type: [],
  35986. pos: [],
  35987. rot: [],
  35988. move: impostor.getParam("mass") !== 0,
  35989. //Supporting older versions of Oimo
  35990. world: this.world
  35991. };
  35992. var impostors = [impostor];
  35993. function addToArray(parent) {
  35994. if (!parent.getChildMeshes)
  35995. return;
  35996. parent.getChildMeshes().forEach(function (m) {
  35997. if (m.physicsImpostor) {
  35998. impostors.push(m.physicsImpostor);
  35999. m.physicsImpostor._init();
  36000. }
  36001. });
  36002. }
  36003. addToArray(impostor.object);
  36004. function checkWithEpsilon(value) {
  36005. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  36006. }
  36007. impostors.forEach(function (i) {
  36008. //get the correct bounding box
  36009. var oldQuaternion = i.object.rotationQuaternion;
  36010. var rot = new OIMO.Euler().setFromQuaternion({
  36011. x: impostor.object.rotationQuaternion.x,
  36012. y: impostor.object.rotationQuaternion.y,
  36013. z: impostor.object.rotationQuaternion.z,
  36014. s: impostor.object.rotationQuaternion.w
  36015. });
  36016. var extendSize = i.getObjectExtendSize();
  36017. if (i === impostor) {
  36018. var center = impostor.getObjectCenter();
  36019. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  36020. //Can also use Array.prototype.push.apply
  36021. bodyConfig.pos.push(center.x);
  36022. bodyConfig.pos.push(center.y);
  36023. bodyConfig.pos.push(center.z);
  36024. //tmp solution
  36025. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  36026. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  36027. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  36028. }
  36029. else {
  36030. bodyConfig.pos.push(i.object.position.x);
  36031. bodyConfig.pos.push(i.object.position.y);
  36032. bodyConfig.pos.push(i.object.position.z);
  36033. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  36034. bodyConfig.rot.push(0);
  36035. bodyConfig.rot.push(0);
  36036. bodyConfig.rot.push(0);
  36037. }
  36038. // register mesh
  36039. switch (i.type) {
  36040. case BABYLON.PhysicsImpostor.ParticleImpostor:
  36041. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  36042. case BABYLON.PhysicsImpostor.SphereImpostor:
  36043. var radiusX = extendSize.x;
  36044. var radiusY = extendSize.y;
  36045. var radiusZ = extendSize.z;
  36046. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  36047. bodyConfig.type.push('sphere');
  36048. //due to the way oimo works with compounds, add 3 times
  36049. bodyConfig.size.push(size);
  36050. bodyConfig.size.push(size);
  36051. bodyConfig.size.push(size);
  36052. break;
  36053. case BABYLON.PhysicsImpostor.CylinderImpostor:
  36054. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  36055. var sizeY = checkWithEpsilon(extendSize.y);
  36056. bodyConfig.type.push('cylinder');
  36057. bodyConfig.size.push(sizeX);
  36058. bodyConfig.size.push(sizeY);
  36059. //due to the way oimo works with compounds, add one more value.
  36060. bodyConfig.size.push(sizeY);
  36061. break;
  36062. case BABYLON.PhysicsImpostor.PlaneImpostor:
  36063. case BABYLON.PhysicsImpostor.BoxImpostor:
  36064. default:
  36065. var sizeX = checkWithEpsilon(extendSize.x);
  36066. var sizeY = checkWithEpsilon(extendSize.y);
  36067. var sizeZ = checkWithEpsilon(extendSize.z);
  36068. bodyConfig.type.push('box');
  36069. bodyConfig.size.push(sizeX);
  36070. bodyConfig.size.push(sizeY);
  36071. bodyConfig.size.push(sizeZ);
  36072. break;
  36073. }
  36074. //actually not needed, but hey...
  36075. i.object.rotationQuaternion = oldQuaternion;
  36076. });
  36077. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  36078. }
  36079. else {
  36080. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  36081. }
  36082. impostor.setDeltaPosition(this._tmpPositionVector);
  36083. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  36084. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  36085. };
  36086. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  36087. //impostor.physicsBody.dispose();
  36088. //Same as : (older oimo versions)
  36089. this.world.removeRigidBody(impostor.physicsBody);
  36090. };
  36091. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  36092. var mainBody = impostorJoint.mainImpostor.physicsBody;
  36093. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  36094. if (!mainBody || !connectedBody) {
  36095. return;
  36096. }
  36097. var jointData = impostorJoint.joint.jointData;
  36098. var options = jointData.nativeParams || {};
  36099. var type;
  36100. var nativeJointData = {
  36101. body1: mainBody,
  36102. body2: connectedBody,
  36103. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  36104. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  36105. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  36106. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  36107. min: options.min,
  36108. max: options.max,
  36109. collision: options.collision || jointData.collision,
  36110. spring: options.spring,
  36111. //supporting older version of Oimo
  36112. world: this.world
  36113. };
  36114. switch (impostorJoint.joint.type) {
  36115. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  36116. type = "jointBall";
  36117. break;
  36118. case BABYLON.PhysicsJoint.SpringJoint:
  36119. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  36120. var springData = jointData;
  36121. nativeJointData.min = springData.length || nativeJointData.min;
  36122. //Max should also be set, just make sure it is at least min
  36123. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  36124. case BABYLON.PhysicsJoint.DistanceJoint:
  36125. type = "jointDistance";
  36126. nativeJointData.max = jointData.maxDistance;
  36127. break;
  36128. case BABYLON.PhysicsJoint.PrismaticJoint:
  36129. type = "jointPrisme";
  36130. break;
  36131. case BABYLON.PhysicsJoint.SliderJoint:
  36132. type = "jointSlide";
  36133. break;
  36134. case BABYLON.PhysicsJoint.WheelJoint:
  36135. type = "jointWheel";
  36136. break;
  36137. case BABYLON.PhysicsJoint.HingeJoint:
  36138. default:
  36139. type = "jointHinge";
  36140. break;
  36141. }
  36142. nativeJointData.type = type;
  36143. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  36144. };
  36145. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  36146. //Bug in Oimo prevents us from disposing a joint in the playground
  36147. //joint.joint.physicsJoint.dispose();
  36148. //So we will bruteforce it!
  36149. try {
  36150. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  36151. }
  36152. catch (e) {
  36153. BABYLON.Tools.Warn(e);
  36154. }
  36155. };
  36156. OimoJSPlugin.prototype.isSupported = function () {
  36157. return OIMO !== undefined;
  36158. };
  36159. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  36160. if (!impostor.physicsBody.sleeping) {
  36161. //TODO check that
  36162. if (impostor.physicsBody.shapes.next) {
  36163. var parentShape = this._getLastShape(impostor.physicsBody);
  36164. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  36165. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  36166. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  36167. }
  36168. else {
  36169. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  36170. }
  36171. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  36172. }
  36173. };
  36174. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  36175. var body = impostor.physicsBody;
  36176. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  36177. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  36178. body.syncShapes();
  36179. body.awake();
  36180. };
  36181. OimoJSPlugin.prototype._getLastShape = function (body) {
  36182. var lastShape = body.shapes;
  36183. while (lastShape.next) {
  36184. lastShape = lastShape.next;
  36185. }
  36186. return lastShape;
  36187. };
  36188. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  36189. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  36190. };
  36191. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  36192. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  36193. };
  36194. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  36195. var v = impostor.physicsBody.linearVelocity;
  36196. if (!v)
  36197. return null;
  36198. return new BABYLON.Vector3(v.x, v.y, v.z);
  36199. };
  36200. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  36201. var v = impostor.physicsBody.angularVelocity;
  36202. if (!v)
  36203. return null;
  36204. return new BABYLON.Vector3(v.x, v.y, v.z);
  36205. };
  36206. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  36207. var staticBody = mass === 0;
  36208. //this will actually set the body's density and not its mass.
  36209. //But this is how oimo treats the mass variable.
  36210. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  36211. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  36212. };
  36213. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  36214. impostor.physicsBody.sleep();
  36215. };
  36216. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  36217. impostor.physicsBody.awake();
  36218. };
  36219. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  36220. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  36221. if (minDistance !== void 0) {
  36222. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  36223. }
  36224. };
  36225. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  36226. //TODO separate rotational and transational motors.
  36227. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  36228. if (motor) {
  36229. motor.setMotor(speed, maxForce);
  36230. }
  36231. };
  36232. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  36233. //TODO separate rotational and transational motors.
  36234. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  36235. if (motor) {
  36236. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  36237. }
  36238. };
  36239. OimoJSPlugin.prototype.dispose = function () {
  36240. this.world.clear();
  36241. };
  36242. return OimoJSPlugin;
  36243. })();
  36244. BABYLON.OimoJSPlugin = OimoJSPlugin;
  36245. })(BABYLON || (BABYLON = {}));
  36246. var BABYLON;
  36247. (function (BABYLON) {
  36248. var DisplayPassPostProcess = (function (_super) {
  36249. __extends(DisplayPassPostProcess, _super);
  36250. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  36251. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  36252. }
  36253. return DisplayPassPostProcess;
  36254. })(BABYLON.PostProcess);
  36255. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  36256. })(BABYLON || (BABYLON = {}));
  36257. var BABYLON;
  36258. (function (BABYLON) {
  36259. var SimplificationSettings = (function () {
  36260. function SimplificationSettings(quality, distance, optimizeMesh) {
  36261. this.quality = quality;
  36262. this.distance = distance;
  36263. this.optimizeMesh = optimizeMesh;
  36264. }
  36265. return SimplificationSettings;
  36266. })();
  36267. BABYLON.SimplificationSettings = SimplificationSettings;
  36268. var SimplificationQueue = (function () {
  36269. function SimplificationQueue() {
  36270. this.running = false;
  36271. this._simplificationArray = [];
  36272. }
  36273. SimplificationQueue.prototype.addTask = function (task) {
  36274. this._simplificationArray.push(task);
  36275. };
  36276. SimplificationQueue.prototype.executeNext = function () {
  36277. var task = this._simplificationArray.pop();
  36278. if (task) {
  36279. this.running = true;
  36280. this.runSimplification(task);
  36281. }
  36282. else {
  36283. this.running = false;
  36284. }
  36285. };
  36286. SimplificationQueue.prototype.runSimplification = function (task) {
  36287. var _this = this;
  36288. if (task.parallelProcessing) {
  36289. //parallel simplifier
  36290. task.settings.forEach(function (setting) {
  36291. var simplifier = _this.getSimplifier(task);
  36292. simplifier.simplify(setting, function (newMesh) {
  36293. task.mesh.addLODLevel(setting.distance, newMesh);
  36294. newMesh.isVisible = true;
  36295. //check if it is the last
  36296. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  36297. //all done, run the success callback.
  36298. task.successCallback();
  36299. }
  36300. _this.executeNext();
  36301. });
  36302. });
  36303. }
  36304. else {
  36305. //single simplifier.
  36306. var simplifier = this.getSimplifier(task);
  36307. var runDecimation = function (setting, callback) {
  36308. simplifier.simplify(setting, function (newMesh) {
  36309. task.mesh.addLODLevel(setting.distance, newMesh);
  36310. newMesh.isVisible = true;
  36311. //run the next quality level
  36312. callback();
  36313. });
  36314. };
  36315. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  36316. runDecimation(task.settings[loop.index], function () {
  36317. loop.executeNext();
  36318. });
  36319. }, function () {
  36320. //execution ended, run the success callback.
  36321. if (task.successCallback) {
  36322. task.successCallback();
  36323. }
  36324. _this.executeNext();
  36325. });
  36326. }
  36327. };
  36328. SimplificationQueue.prototype.getSimplifier = function (task) {
  36329. switch (task.simplificationType) {
  36330. case SimplificationType.QUADRATIC:
  36331. default:
  36332. return new QuadraticErrorSimplification(task.mesh);
  36333. }
  36334. };
  36335. return SimplificationQueue;
  36336. })();
  36337. BABYLON.SimplificationQueue = SimplificationQueue;
  36338. /**
  36339. * The implemented types of simplification.
  36340. * At the moment only Quadratic Error Decimation is implemented.
  36341. */
  36342. (function (SimplificationType) {
  36343. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  36344. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  36345. var SimplificationType = BABYLON.SimplificationType;
  36346. var DecimationTriangle = (function () {
  36347. function DecimationTriangle(vertices) {
  36348. this.vertices = vertices;
  36349. this.error = new Array(4);
  36350. this.deleted = false;
  36351. this.isDirty = false;
  36352. this.deletePending = false;
  36353. this.borderFactor = 0;
  36354. }
  36355. return DecimationTriangle;
  36356. })();
  36357. BABYLON.DecimationTriangle = DecimationTriangle;
  36358. var DecimationVertex = (function () {
  36359. function DecimationVertex(position, id) {
  36360. this.position = position;
  36361. this.id = id;
  36362. this.isBorder = true;
  36363. this.q = new QuadraticMatrix();
  36364. this.triangleCount = 0;
  36365. this.triangleStart = 0;
  36366. this.originalOffsets = [];
  36367. }
  36368. DecimationVertex.prototype.updatePosition = function (newPosition) {
  36369. this.position.copyFrom(newPosition);
  36370. };
  36371. return DecimationVertex;
  36372. })();
  36373. BABYLON.DecimationVertex = DecimationVertex;
  36374. var QuadraticMatrix = (function () {
  36375. function QuadraticMatrix(data) {
  36376. this.data = new Array(10);
  36377. for (var i = 0; i < 10; ++i) {
  36378. if (data && data[i]) {
  36379. this.data[i] = data[i];
  36380. }
  36381. else {
  36382. this.data[i] = 0;
  36383. }
  36384. }
  36385. }
  36386. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  36387. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  36388. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  36389. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  36390. return det;
  36391. };
  36392. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  36393. for (var i = 0; i < 10; ++i) {
  36394. this.data[i] += matrix.data[i];
  36395. }
  36396. };
  36397. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  36398. for (var i = 0; i < 10; ++i) {
  36399. this.data[i] += data[i];
  36400. }
  36401. };
  36402. QuadraticMatrix.prototype.add = function (matrix) {
  36403. var m = new QuadraticMatrix();
  36404. for (var i = 0; i < 10; ++i) {
  36405. m.data[i] = this.data[i] + matrix.data[i];
  36406. }
  36407. return m;
  36408. };
  36409. QuadraticMatrix.FromData = function (a, b, c, d) {
  36410. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  36411. };
  36412. //returning an array to avoid garbage collection
  36413. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  36414. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  36415. };
  36416. return QuadraticMatrix;
  36417. })();
  36418. BABYLON.QuadraticMatrix = QuadraticMatrix;
  36419. var Reference = (function () {
  36420. function Reference(vertexId, triangleId) {
  36421. this.vertexId = vertexId;
  36422. this.triangleId = triangleId;
  36423. }
  36424. return Reference;
  36425. })();
  36426. BABYLON.Reference = Reference;
  36427. /**
  36428. * An implementation of the Quadratic Error simplification algorithm.
  36429. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  36430. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  36431. * @author RaananW
  36432. */
  36433. var QuadraticErrorSimplification = (function () {
  36434. function QuadraticErrorSimplification(_mesh) {
  36435. this._mesh = _mesh;
  36436. this.initialized = false;
  36437. this.syncIterations = 5000;
  36438. this.aggressiveness = 7;
  36439. this.decimationIterations = 100;
  36440. this.boundingBoxEpsilon = BABYLON.Epsilon;
  36441. }
  36442. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  36443. var _this = this;
  36444. this.initDecimatedMesh();
  36445. //iterating through the submeshes array, one after the other.
  36446. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  36447. _this.initWithMesh(loop.index, function () {
  36448. _this.runDecimation(settings, loop.index, function () {
  36449. loop.executeNext();
  36450. });
  36451. }, settings.optimizeMesh);
  36452. }, function () {
  36453. setTimeout(function () {
  36454. successCallback(_this._reconstructedMesh);
  36455. }, 0);
  36456. });
  36457. };
  36458. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  36459. var _this = this;
  36460. var gCount = 0;
  36461. triangle.vertices.forEach(function (vertex) {
  36462. var count = 0;
  36463. var vPos = vertex.position;
  36464. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  36465. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  36466. ++count;
  36467. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  36468. ++count;
  36469. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  36470. ++count;
  36471. if (count > 1) {
  36472. ++gCount;
  36473. }
  36474. ;
  36475. });
  36476. if (gCount > 1) {
  36477. console.log(triangle, gCount);
  36478. }
  36479. return gCount > 1;
  36480. };
  36481. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  36482. var _this = this;
  36483. var targetCount = ~~(this.triangles.length * settings.quality);
  36484. var deletedTriangles = 0;
  36485. var triangleCount = this.triangles.length;
  36486. var iterationFunction = function (iteration, callback) {
  36487. setTimeout(function () {
  36488. if (iteration % 5 === 0) {
  36489. _this.updateMesh(iteration === 0);
  36490. }
  36491. for (var i = 0; i < _this.triangles.length; ++i) {
  36492. _this.triangles[i].isDirty = false;
  36493. }
  36494. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  36495. var trianglesIterator = function (i) {
  36496. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  36497. var t = _this.triangles[tIdx];
  36498. if (!t)
  36499. return;
  36500. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  36501. return;
  36502. }
  36503. for (var j = 0; j < 3; ++j) {
  36504. if (t.error[j] < threshold) {
  36505. var deleted0 = [];
  36506. var deleted1 = [];
  36507. var v0 = t.vertices[j];
  36508. var v1 = t.vertices[(j + 1) % 3];
  36509. if (v0.isBorder || v1.isBorder)
  36510. continue;
  36511. var p = BABYLON.Vector3.Zero();
  36512. var n = BABYLON.Vector3.Zero();
  36513. var uv = BABYLON.Vector2.Zero();
  36514. var color = new BABYLON.Color4(0, 0, 0, 1);
  36515. _this.calculateError(v0, v1, p, n, uv, color);
  36516. var delTr = [];
  36517. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  36518. continue;
  36519. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  36520. continue;
  36521. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  36522. continue;
  36523. var uniqueArray = [];
  36524. delTr.forEach(function (deletedT) {
  36525. if (uniqueArray.indexOf(deletedT) === -1) {
  36526. deletedT.deletePending = true;
  36527. uniqueArray.push(deletedT);
  36528. }
  36529. });
  36530. if (uniqueArray.length % 2 !== 0) {
  36531. continue;
  36532. }
  36533. v0.q = v1.q.add(v0.q);
  36534. v0.updatePosition(p);
  36535. var tStart = _this.references.length;
  36536. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  36537. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  36538. var tCount = _this.references.length - tStart;
  36539. if (tCount <= v0.triangleCount) {
  36540. if (tCount) {
  36541. for (var c = 0; c < tCount; c++) {
  36542. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  36543. }
  36544. }
  36545. }
  36546. else {
  36547. v0.triangleStart = tStart;
  36548. }
  36549. v0.triangleCount = tCount;
  36550. break;
  36551. }
  36552. }
  36553. };
  36554. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  36555. }, 0);
  36556. };
  36557. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  36558. if (triangleCount - deletedTriangles <= targetCount)
  36559. loop.breakLoop();
  36560. else {
  36561. iterationFunction(loop.index, function () {
  36562. loop.executeNext();
  36563. });
  36564. }
  36565. }, function () {
  36566. setTimeout(function () {
  36567. //reconstruct this part of the mesh
  36568. _this.reconstructMesh(submeshIndex);
  36569. successCallback();
  36570. }, 0);
  36571. });
  36572. };
  36573. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  36574. var _this = this;
  36575. this.vertices = [];
  36576. this.triangles = [];
  36577. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36578. var indices = this._mesh.getIndices();
  36579. var submesh = this._mesh.subMeshes[submeshIndex];
  36580. var findInVertices = function (positionToSearch) {
  36581. if (optimizeMesh) {
  36582. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  36583. if (_this.vertices[ii].position.equals(positionToSearch)) {
  36584. return _this.vertices[ii];
  36585. }
  36586. }
  36587. }
  36588. return null;
  36589. };
  36590. var vertexReferences = [];
  36591. var vertexInit = function (i) {
  36592. var offset = i + submesh.verticesStart;
  36593. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  36594. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  36595. vertex.originalOffsets.push(offset);
  36596. if (vertex.id === _this.vertices.length) {
  36597. _this.vertices.push(vertex);
  36598. }
  36599. vertexReferences.push(vertex.id);
  36600. };
  36601. //var totalVertices = mesh.getTotalVertices();
  36602. var totalVertices = submesh.verticesCount;
  36603. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  36604. var indicesInit = function (i) {
  36605. var offset = (submesh.indexStart / 3) + i;
  36606. var pos = (offset * 3);
  36607. var i0 = indices[pos + 0];
  36608. var i1 = indices[pos + 1];
  36609. var i2 = indices[pos + 2];
  36610. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  36611. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  36612. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  36613. var triangle = new DecimationTriangle([v0, v1, v2]);
  36614. triangle.originalOffset = pos;
  36615. _this.triangles.push(triangle);
  36616. };
  36617. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  36618. _this.init(callback);
  36619. });
  36620. });
  36621. };
  36622. QuadraticErrorSimplification.prototype.init = function (callback) {
  36623. var _this = this;
  36624. var triangleInit1 = function (i) {
  36625. var t = _this.triangles[i];
  36626. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  36627. for (var j = 0; j < 3; j++) {
  36628. 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))));
  36629. }
  36630. };
  36631. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  36632. var triangleInit2 = function (i) {
  36633. var t = _this.triangles[i];
  36634. for (var j = 0; j < 3; ++j) {
  36635. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  36636. }
  36637. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  36638. };
  36639. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  36640. _this.initialized = true;
  36641. callback();
  36642. });
  36643. });
  36644. };
  36645. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  36646. var newTriangles = [];
  36647. var i;
  36648. for (i = 0; i < this.vertices.length; ++i) {
  36649. this.vertices[i].triangleCount = 0;
  36650. }
  36651. var t;
  36652. var j;
  36653. for (i = 0; i < this.triangles.length; ++i) {
  36654. if (!this.triangles[i].deleted) {
  36655. t = this.triangles[i];
  36656. for (j = 0; j < 3; ++j) {
  36657. t.vertices[j].triangleCount = 1;
  36658. }
  36659. newTriangles.push(t);
  36660. }
  36661. }
  36662. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  36663. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  36664. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  36665. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  36666. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36667. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36668. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36669. var vertexCount = 0;
  36670. for (i = 0; i < this.vertices.length; ++i) {
  36671. var vertex = this.vertices[i];
  36672. vertex.id = vertexCount;
  36673. if (vertex.triangleCount) {
  36674. vertex.originalOffsets.forEach(function (originalOffset) {
  36675. newPositionData.push(vertex.position.x);
  36676. newPositionData.push(vertex.position.y);
  36677. newPositionData.push(vertex.position.z);
  36678. newNormalData.push(normalData[originalOffset * 3]);
  36679. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  36680. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  36681. if (uvs && uvs.length) {
  36682. newUVsData.push(uvs[(originalOffset * 2)]);
  36683. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  36684. }
  36685. else if (colorsData && colorsData.length) {
  36686. newColorsData.push(colorsData[(originalOffset * 4)]);
  36687. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  36688. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  36689. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  36690. }
  36691. ++vertexCount;
  36692. });
  36693. }
  36694. }
  36695. var startingIndex = this._reconstructedMesh.getTotalIndices();
  36696. var startingVertex = this._reconstructedMesh.getTotalVertices();
  36697. var submeshesArray = this._reconstructedMesh.subMeshes;
  36698. this._reconstructedMesh.subMeshes = [];
  36699. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  36700. var originalIndices = this._mesh.getIndices();
  36701. for (i = 0; i < newTriangles.length; ++i) {
  36702. t = newTriangles[i]; //now get the new referencing point for each vertex
  36703. [0, 1, 2].forEach(function (idx) {
  36704. var id = originalIndices[t.originalOffset + idx];
  36705. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  36706. if (offset < 0)
  36707. offset = 0;
  36708. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  36709. });
  36710. }
  36711. //overwriting the old vertex buffers and indices.
  36712. this._reconstructedMesh.setIndices(newIndicesArray);
  36713. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  36714. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  36715. if (newUVsData.length > 0)
  36716. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  36717. if (newColorsData.length > 0)
  36718. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  36719. //create submesh
  36720. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  36721. if (submeshIndex > 0) {
  36722. this._reconstructedMesh.subMeshes = [];
  36723. submeshesArray.forEach(function (submesh) {
  36724. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  36725. });
  36726. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  36727. }
  36728. };
  36729. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  36730. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  36731. this._reconstructedMesh.material = this._mesh.material;
  36732. this._reconstructedMesh.parent = this._mesh.parent;
  36733. this._reconstructedMesh.isVisible = false;
  36734. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  36735. };
  36736. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  36737. for (var i = 0; i < vertex1.triangleCount; ++i) {
  36738. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  36739. if (t.deleted)
  36740. continue;
  36741. var s = this.references[vertex1.triangleStart + i].vertexId;
  36742. var v1 = t.vertices[(s + 1) % 3];
  36743. var v2 = t.vertices[(s + 2) % 3];
  36744. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  36745. deletedArray[i] = true;
  36746. delTr.push(t);
  36747. continue;
  36748. }
  36749. var d1 = v1.position.subtract(point);
  36750. d1 = d1.normalize();
  36751. var d2 = v2.position.subtract(point);
  36752. d2 = d2.normalize();
  36753. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  36754. return true;
  36755. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  36756. deletedArray[i] = false;
  36757. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  36758. return true;
  36759. }
  36760. return false;
  36761. };
  36762. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  36763. var newDeleted = deletedTriangles;
  36764. for (var i = 0; i < vertex.triangleCount; ++i) {
  36765. var ref = this.references[vertex.triangleStart + i];
  36766. var t = this.triangles[ref.triangleId];
  36767. if (t.deleted)
  36768. continue;
  36769. if (deletedArray[i] && t.deletePending) {
  36770. t.deleted = true;
  36771. newDeleted++;
  36772. continue;
  36773. }
  36774. t.vertices[ref.vertexId] = origVertex;
  36775. t.isDirty = true;
  36776. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  36777. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  36778. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  36779. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  36780. this.references.push(ref);
  36781. }
  36782. return newDeleted;
  36783. };
  36784. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  36785. for (var i = 0; i < this.vertices.length; ++i) {
  36786. var vCount = [];
  36787. var vId = [];
  36788. var v = this.vertices[i];
  36789. var j;
  36790. for (j = 0; j < v.triangleCount; ++j) {
  36791. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  36792. for (var ii = 0; ii < 3; ii++) {
  36793. var ofs = 0;
  36794. var vv = triangle.vertices[ii];
  36795. while (ofs < vCount.length) {
  36796. if (vId[ofs] === vv.id)
  36797. break;
  36798. ++ofs;
  36799. }
  36800. if (ofs === vCount.length) {
  36801. vCount.push(1);
  36802. vId.push(vv.id);
  36803. }
  36804. else {
  36805. vCount[ofs]++;
  36806. }
  36807. }
  36808. }
  36809. for (j = 0; j < vCount.length; ++j) {
  36810. if (vCount[j] === 1) {
  36811. this.vertices[vId[j]].isBorder = true;
  36812. }
  36813. else {
  36814. this.vertices[vId[j]].isBorder = false;
  36815. }
  36816. }
  36817. }
  36818. };
  36819. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  36820. if (identifyBorders === void 0) { identifyBorders = false; }
  36821. var i;
  36822. if (!identifyBorders) {
  36823. var newTrianglesVector = [];
  36824. for (i = 0; i < this.triangles.length; ++i) {
  36825. if (!this.triangles[i].deleted) {
  36826. newTrianglesVector.push(this.triangles[i]);
  36827. }
  36828. }
  36829. this.triangles = newTrianglesVector;
  36830. }
  36831. for (i = 0; i < this.vertices.length; ++i) {
  36832. this.vertices[i].triangleCount = 0;
  36833. this.vertices[i].triangleStart = 0;
  36834. }
  36835. var t;
  36836. var j;
  36837. var v;
  36838. for (i = 0; i < this.triangles.length; ++i) {
  36839. t = this.triangles[i];
  36840. for (j = 0; j < 3; ++j) {
  36841. v = t.vertices[j];
  36842. v.triangleCount++;
  36843. }
  36844. }
  36845. var tStart = 0;
  36846. for (i = 0; i < this.vertices.length; ++i) {
  36847. this.vertices[i].triangleStart = tStart;
  36848. tStart += this.vertices[i].triangleCount;
  36849. this.vertices[i].triangleCount = 0;
  36850. }
  36851. var newReferences = new Array(this.triangles.length * 3);
  36852. for (i = 0; i < this.triangles.length; ++i) {
  36853. t = this.triangles[i];
  36854. for (j = 0; j < 3; ++j) {
  36855. v = t.vertices[j];
  36856. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  36857. v.triangleCount++;
  36858. }
  36859. }
  36860. this.references = newReferences;
  36861. if (identifyBorders) {
  36862. this.identifyBorder();
  36863. }
  36864. };
  36865. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  36866. var x = point.x;
  36867. var y = point.y;
  36868. var z = point.z;
  36869. 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
  36870. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  36871. };
  36872. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  36873. var q = vertex1.q.add(vertex2.q);
  36874. var border = vertex1.isBorder && vertex2.isBorder;
  36875. var error = 0;
  36876. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  36877. if (qDet !== 0 && !border) {
  36878. if (!pointResult) {
  36879. pointResult = BABYLON.Vector3.Zero();
  36880. }
  36881. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  36882. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  36883. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  36884. error = this.vertexError(q, pointResult);
  36885. }
  36886. else {
  36887. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  36888. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  36889. var error1 = this.vertexError(q, vertex1.position);
  36890. var error2 = this.vertexError(q, vertex2.position);
  36891. var error3 = this.vertexError(q, p3);
  36892. error = Math.min(error1, error2, error3);
  36893. if (error === error1) {
  36894. if (pointResult) {
  36895. pointResult.copyFrom(vertex1.position);
  36896. }
  36897. }
  36898. else if (error === error2) {
  36899. if (pointResult) {
  36900. pointResult.copyFrom(vertex2.position);
  36901. }
  36902. }
  36903. else {
  36904. if (pointResult) {
  36905. pointResult.copyFrom(p3);
  36906. }
  36907. }
  36908. }
  36909. return error;
  36910. };
  36911. return QuadraticErrorSimplification;
  36912. })();
  36913. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  36914. })(BABYLON || (BABYLON = {}));
  36915. var BABYLON;
  36916. (function (BABYLON) {
  36917. var serializedGeometries = [];
  36918. var serializeGeometry = function (geometry, serializationGeometries) {
  36919. if (serializedGeometries[geometry.id]) {
  36920. return;
  36921. }
  36922. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  36923. serializationGeometries.boxes.push(geometry.serialize());
  36924. }
  36925. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  36926. serializationGeometries.spheres.push(geometry.serialize());
  36927. }
  36928. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  36929. serializationGeometries.cylinders.push(geometry.serialize());
  36930. }
  36931. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  36932. serializationGeometries.toruses.push(geometry.serialize());
  36933. }
  36934. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  36935. serializationGeometries.grounds.push(geometry.serialize());
  36936. }
  36937. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  36938. serializationGeometries.planes.push(geometry.serialize());
  36939. }
  36940. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  36941. serializationGeometries.torusKnots.push(geometry.serialize());
  36942. }
  36943. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  36944. throw new Error("Unknown primitive type");
  36945. }
  36946. else {
  36947. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  36948. }
  36949. serializedGeometries[geometry.id] = true;
  36950. };
  36951. var serializeMesh = function (mesh, serializationScene) {
  36952. var serializationObject = {};
  36953. serializationObject.name = mesh.name;
  36954. serializationObject.id = mesh.id;
  36955. if (BABYLON.Tags.HasTags(mesh)) {
  36956. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  36957. }
  36958. serializationObject.position = mesh.position.asArray();
  36959. if (mesh.rotationQuaternion) {
  36960. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  36961. }
  36962. else if (mesh.rotation) {
  36963. serializationObject.rotation = mesh.rotation.asArray();
  36964. }
  36965. serializationObject.scaling = mesh.scaling.asArray();
  36966. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  36967. serializationObject.isEnabled = mesh.isEnabled();
  36968. serializationObject.isVisible = mesh.isVisible;
  36969. serializationObject.infiniteDistance = mesh.infiniteDistance;
  36970. serializationObject.pickable = mesh.isPickable;
  36971. serializationObject.receiveShadows = mesh.receiveShadows;
  36972. serializationObject.billboardMode = mesh.billboardMode;
  36973. serializationObject.visibility = mesh.visibility;
  36974. serializationObject.checkCollisions = mesh.checkCollisions;
  36975. // Parent
  36976. if (mesh.parent) {
  36977. serializationObject.parentId = mesh.parent.id;
  36978. }
  36979. // Geometry
  36980. var geometry = mesh._geometry;
  36981. if (geometry) {
  36982. var geometryId = geometry.id;
  36983. serializationObject.geometryId = geometryId;
  36984. if (!mesh.getScene().getGeometryByID(geometryId)) {
  36985. // 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
  36986. serializeGeometry(geometry, serializationScene.geometries);
  36987. }
  36988. // SubMeshes
  36989. serializationObject.subMeshes = [];
  36990. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36991. var subMesh = mesh.subMeshes[subIndex];
  36992. serializationObject.subMeshes.push({
  36993. materialIndex: subMesh.materialIndex,
  36994. verticesStart: subMesh.verticesStart,
  36995. verticesCount: subMesh.verticesCount,
  36996. indexStart: subMesh.indexStart,
  36997. indexCount: subMesh.indexCount
  36998. });
  36999. }
  37000. }
  37001. // Material
  37002. if (mesh.material) {
  37003. serializationObject.materialId = mesh.material.id;
  37004. }
  37005. else {
  37006. mesh.material = null;
  37007. }
  37008. // Skeleton
  37009. if (mesh.skeleton) {
  37010. serializationObject.skeletonId = mesh.skeleton.id;
  37011. }
  37012. // Physics
  37013. //TODO implement correct serialization for physics impostors.
  37014. if (mesh.getPhysicsImpostor()) {
  37015. serializationObject.physicsMass = mesh.getPhysicsMass();
  37016. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  37017. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  37018. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  37019. }
  37020. // Instances
  37021. serializationObject.instances = [];
  37022. for (var index = 0; index < mesh.instances.length; index++) {
  37023. var instance = mesh.instances[index];
  37024. var serializationInstance = {
  37025. name: instance.name,
  37026. position: instance.position.asArray(),
  37027. scaling: instance.scaling.asArray()
  37028. };
  37029. if (instance.rotationQuaternion) {
  37030. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  37031. }
  37032. else if (instance.rotation) {
  37033. serializationInstance.rotation = instance.rotation.asArray();
  37034. }
  37035. serializationObject.instances.push(serializationInstance);
  37036. // Animations
  37037. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  37038. serializationInstance.ranges = instance.serializeAnimationRanges();
  37039. }
  37040. // Animations
  37041. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  37042. serializationObject.ranges = mesh.serializeAnimationRanges();
  37043. // Layer mask
  37044. serializationObject.layerMask = mesh.layerMask;
  37045. // Action Manager
  37046. if (mesh.actionManager) {
  37047. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  37048. }
  37049. return serializationObject;
  37050. };
  37051. var finalizeSingleMesh = function (mesh, serializationObject) {
  37052. //only works if the mesh is already loaded
  37053. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  37054. //serialize material
  37055. if (mesh.material) {
  37056. if (mesh.material instanceof BABYLON.StandardMaterial) {
  37057. serializationObject.materials = serializationObject.materials || [];
  37058. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  37059. serializationObject.materials.push(mesh.material.serialize());
  37060. }
  37061. }
  37062. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  37063. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  37064. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  37065. serializationObject.multiMaterials.push(mesh.material.serialize());
  37066. }
  37067. }
  37068. }
  37069. //serialize geometry
  37070. var geometry = mesh._geometry;
  37071. if (geometry) {
  37072. if (!serializationObject.geometries) {
  37073. serializationObject.geometries = {};
  37074. serializationObject.geometries.boxes = [];
  37075. serializationObject.geometries.spheres = [];
  37076. serializationObject.geometries.cylinders = [];
  37077. serializationObject.geometries.toruses = [];
  37078. serializationObject.geometries.grounds = [];
  37079. serializationObject.geometries.planes = [];
  37080. serializationObject.geometries.torusKnots = [];
  37081. serializationObject.geometries.vertexData = [];
  37082. }
  37083. serializeGeometry(geometry, serializationObject.geometries);
  37084. }
  37085. // Skeletons
  37086. if (mesh.skeleton) {
  37087. serializationObject.skeletons = serializationObject.skeletons || [];
  37088. serializationObject.skeletons.push(mesh.skeleton.serialize());
  37089. }
  37090. //serialize the actual mesh
  37091. serializationObject.meshes = serializationObject.meshes || [];
  37092. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  37093. }
  37094. };
  37095. var SceneSerializer = (function () {
  37096. function SceneSerializer() {
  37097. }
  37098. SceneSerializer.ClearCache = function () {
  37099. serializedGeometries = [];
  37100. };
  37101. SceneSerializer.Serialize = function (scene) {
  37102. var serializationObject = {};
  37103. // Scene
  37104. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  37105. serializationObject.autoClear = scene.autoClear;
  37106. serializationObject.clearColor = scene.clearColor.asArray();
  37107. serializationObject.ambientColor = scene.ambientColor.asArray();
  37108. serializationObject.gravity = scene.gravity.asArray();
  37109. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  37110. serializationObject.workerCollisions = scene.workerCollisions;
  37111. // Fog
  37112. if (scene.fogMode && scene.fogMode !== 0) {
  37113. serializationObject.fogMode = scene.fogMode;
  37114. serializationObject.fogColor = scene.fogColor.asArray();
  37115. serializationObject.fogStart = scene.fogStart;
  37116. serializationObject.fogEnd = scene.fogEnd;
  37117. serializationObject.fogDensity = scene.fogDensity;
  37118. }
  37119. //Physics
  37120. if (scene.isPhysicsEnabled()) {
  37121. serializationObject.physicsEnabled = true;
  37122. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  37123. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  37124. }
  37125. // Lights
  37126. serializationObject.lights = [];
  37127. var index;
  37128. var light;
  37129. for (index = 0; index < scene.lights.length; index++) {
  37130. light = scene.lights[index];
  37131. serializationObject.lights.push(light.serialize());
  37132. }
  37133. // Cameras
  37134. serializationObject.cameras = [];
  37135. for (index = 0; index < scene.cameras.length; index++) {
  37136. var camera = scene.cameras[index];
  37137. serializationObject.cameras.push(camera.serialize());
  37138. }
  37139. if (scene.activeCamera) {
  37140. serializationObject.activeCameraID = scene.activeCamera.id;
  37141. }
  37142. // Animations
  37143. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  37144. // Materials
  37145. serializationObject.materials = [];
  37146. serializationObject.multiMaterials = [];
  37147. var material;
  37148. for (index = 0; index < scene.materials.length; index++) {
  37149. material = scene.materials[index];
  37150. serializationObject.materials.push(material.serialize());
  37151. }
  37152. // MultiMaterials
  37153. serializationObject.multiMaterials = [];
  37154. for (index = 0; index < scene.multiMaterials.length; index++) {
  37155. var multiMaterial = scene.multiMaterials[index];
  37156. serializationObject.multiMaterials.push(multiMaterial.serialize());
  37157. }
  37158. // Skeletons
  37159. serializationObject.skeletons = [];
  37160. for (index = 0; index < scene.skeletons.length; index++) {
  37161. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  37162. }
  37163. // Geometries
  37164. serializationObject.geometries = {};
  37165. serializationObject.geometries.boxes = [];
  37166. serializationObject.geometries.spheres = [];
  37167. serializationObject.geometries.cylinders = [];
  37168. serializationObject.geometries.toruses = [];
  37169. serializationObject.geometries.grounds = [];
  37170. serializationObject.geometries.planes = [];
  37171. serializationObject.geometries.torusKnots = [];
  37172. serializationObject.geometries.vertexData = [];
  37173. serializedGeometries = [];
  37174. var geometries = scene.getGeometries();
  37175. for (index = 0; index < geometries.length; index++) {
  37176. var geometry = geometries[index];
  37177. if (geometry.isReady()) {
  37178. serializeGeometry(geometry, serializationObject.geometries);
  37179. }
  37180. }
  37181. // Meshes
  37182. serializationObject.meshes = [];
  37183. for (index = 0; index < scene.meshes.length; index++) {
  37184. var abstractMesh = scene.meshes[index];
  37185. if (abstractMesh instanceof BABYLON.Mesh) {
  37186. var mesh = abstractMesh;
  37187. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  37188. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  37189. }
  37190. }
  37191. }
  37192. // Particles Systems
  37193. serializationObject.particleSystems = [];
  37194. for (index = 0; index < scene.particleSystems.length; index++) {
  37195. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  37196. }
  37197. // Lens flares
  37198. serializationObject.lensFlareSystems = [];
  37199. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  37200. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  37201. }
  37202. // Shadows
  37203. serializationObject.shadowGenerators = [];
  37204. for (index = 0; index < scene.lights.length; index++) {
  37205. light = scene.lights[index];
  37206. if (light.getShadowGenerator()) {
  37207. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  37208. }
  37209. }
  37210. // Action Manager
  37211. if (scene.actionManager) {
  37212. serializationObject.actions = scene.actionManager.serialize("scene");
  37213. }
  37214. return serializationObject;
  37215. };
  37216. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  37217. if (withParents === void 0) { withParents = false; }
  37218. if (withChildren === void 0) { withChildren = false; }
  37219. var serializationObject = {};
  37220. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  37221. if (withParents || withChildren) {
  37222. //deliberate for loop! not for each, appended should be processed as well.
  37223. for (var i = 0; i < toSerialize.length; ++i) {
  37224. if (withChildren) {
  37225. toSerialize[i].getDescendants().forEach(function (node) {
  37226. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  37227. toSerialize.push(node);
  37228. }
  37229. });
  37230. }
  37231. //make sure the array doesn't contain the object already
  37232. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  37233. toSerialize.push(toSerialize[i].parent);
  37234. }
  37235. }
  37236. }
  37237. toSerialize.forEach(function (mesh) {
  37238. finalizeSingleMesh(mesh, serializationObject);
  37239. });
  37240. return serializationObject;
  37241. };
  37242. return SceneSerializer;
  37243. })();
  37244. BABYLON.SceneSerializer = SceneSerializer;
  37245. })(BABYLON || (BABYLON = {}));
  37246. var BABYLON;
  37247. (function (BABYLON) {
  37248. // Unique ID when we import meshes from Babylon to CSG
  37249. var currentCSGMeshId = 0;
  37250. // # class Vertex
  37251. // Represents a vertex of a polygon. Use your own vertex class instead of this
  37252. // one to provide additional features like texture coordinates and vertex
  37253. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  37254. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  37255. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  37256. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  37257. // is not used anywhere else.
  37258. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  37259. var Vertex = (function () {
  37260. function Vertex(pos, normal, uv) {
  37261. this.pos = pos;
  37262. this.normal = normal;
  37263. this.uv = uv;
  37264. }
  37265. Vertex.prototype.clone = function () {
  37266. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  37267. };
  37268. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  37269. // orientation of a polygon is flipped.
  37270. Vertex.prototype.flip = function () {
  37271. this.normal = this.normal.scale(-1);
  37272. };
  37273. // Create a new vertex between this vertex and `other` by linearly
  37274. // interpolating all properties using a parameter of `t`. Subclasses should
  37275. // override this to interpolate additional properties.
  37276. Vertex.prototype.interpolate = function (other, t) {
  37277. 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));
  37278. };
  37279. return Vertex;
  37280. })();
  37281. // # class Plane
  37282. // Represents a plane in 3D space.
  37283. var Plane = (function () {
  37284. function Plane(normal, w) {
  37285. this.normal = normal;
  37286. this.w = w;
  37287. }
  37288. Plane.FromPoints = function (a, b, c) {
  37289. var v0 = c.subtract(a);
  37290. var v1 = b.subtract(a);
  37291. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  37292. return null;
  37293. }
  37294. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  37295. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  37296. };
  37297. Plane.prototype.clone = function () {
  37298. return new Plane(this.normal.clone(), this.w);
  37299. };
  37300. Plane.prototype.flip = function () {
  37301. this.normal.scaleInPlace(-1);
  37302. this.w = -this.w;
  37303. };
  37304. // Split `polygon` by this plane if needed, then put the polygon or polygon
  37305. // fragments in the appropriate lists. Coplanar polygons go into either
  37306. // `coplanarFront` or `coplanarBack` depending on their orientation with
  37307. // respect to this plane. Polygons in front or in back of this plane go into
  37308. // either `front` or `back`.
  37309. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  37310. var COPLANAR = 0;
  37311. var FRONT = 1;
  37312. var BACK = 2;
  37313. var SPANNING = 3;
  37314. // Classify each point as well as the entire polygon into one of the above
  37315. // four classes.
  37316. var polygonType = 0;
  37317. var types = [];
  37318. var i;
  37319. var t;
  37320. for (i = 0; i < polygon.vertices.length; i++) {
  37321. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  37322. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  37323. polygonType |= type;
  37324. types.push(type);
  37325. }
  37326. // Put the polygon in the correct list, splitting it when necessary.
  37327. switch (polygonType) {
  37328. case COPLANAR:
  37329. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  37330. break;
  37331. case FRONT:
  37332. front.push(polygon);
  37333. break;
  37334. case BACK:
  37335. back.push(polygon);
  37336. break;
  37337. case SPANNING:
  37338. var f = [], b = [];
  37339. for (i = 0; i < polygon.vertices.length; i++) {
  37340. var j = (i + 1) % polygon.vertices.length;
  37341. var ti = types[i], tj = types[j];
  37342. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  37343. if (ti !== BACK)
  37344. f.push(vi);
  37345. if (ti !== FRONT)
  37346. b.push(ti !== BACK ? vi.clone() : vi);
  37347. if ((ti | tj) === SPANNING) {
  37348. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  37349. var v = vi.interpolate(vj, t);
  37350. f.push(v);
  37351. b.push(v.clone());
  37352. }
  37353. }
  37354. var poly;
  37355. if (f.length >= 3) {
  37356. poly = new Polygon(f, polygon.shared);
  37357. if (poly.plane)
  37358. front.push(poly);
  37359. }
  37360. if (b.length >= 3) {
  37361. poly = new Polygon(b, polygon.shared);
  37362. if (poly.plane)
  37363. back.push(poly);
  37364. }
  37365. break;
  37366. }
  37367. };
  37368. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  37369. // point is on the plane.
  37370. Plane.EPSILON = 1e-5;
  37371. return Plane;
  37372. })();
  37373. // # class Polygon
  37374. // Represents a convex polygon. The vertices used to initialize a polygon must
  37375. // be coplanar and form a convex loop.
  37376. //
  37377. // Each convex polygon has a `shared` property, which is shared between all
  37378. // polygons that are clones of each other or were split from the same polygon.
  37379. // This can be used to define per-polygon properties (such as surface color).
  37380. var Polygon = (function () {
  37381. function Polygon(vertices, shared) {
  37382. this.vertices = vertices;
  37383. this.shared = shared;
  37384. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  37385. }
  37386. Polygon.prototype.clone = function () {
  37387. var vertices = this.vertices.map(function (v) { return v.clone(); });
  37388. return new Polygon(vertices, this.shared);
  37389. };
  37390. Polygon.prototype.flip = function () {
  37391. this.vertices.reverse().map(function (v) { v.flip(); });
  37392. this.plane.flip();
  37393. };
  37394. return Polygon;
  37395. })();
  37396. // # class Node
  37397. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  37398. // by picking a polygon to split along. That polygon (and all other coplanar
  37399. // polygons) are added directly to that node and the other polygons are added to
  37400. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  37401. // no distinction between internal and leaf nodes.
  37402. var Node = (function () {
  37403. function Node(polygons) {
  37404. this.plane = null;
  37405. this.front = null;
  37406. this.back = null;
  37407. this.polygons = [];
  37408. if (polygons) {
  37409. this.build(polygons);
  37410. }
  37411. }
  37412. Node.prototype.clone = function () {
  37413. var node = new Node();
  37414. node.plane = this.plane && this.plane.clone();
  37415. node.front = this.front && this.front.clone();
  37416. node.back = this.back && this.back.clone();
  37417. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  37418. return node;
  37419. };
  37420. // Convert solid space to empty space and empty space to solid space.
  37421. Node.prototype.invert = function () {
  37422. for (var i = 0; i < this.polygons.length; i++) {
  37423. this.polygons[i].flip();
  37424. }
  37425. if (this.plane) {
  37426. this.plane.flip();
  37427. }
  37428. if (this.front) {
  37429. this.front.invert();
  37430. }
  37431. if (this.back) {
  37432. this.back.invert();
  37433. }
  37434. var temp = this.front;
  37435. this.front = this.back;
  37436. this.back = temp;
  37437. };
  37438. // Recursively remove all polygons in `polygons` that are inside this BSP
  37439. // tree.
  37440. Node.prototype.clipPolygons = function (polygons) {
  37441. if (!this.plane)
  37442. return polygons.slice();
  37443. var front = [], back = [];
  37444. for (var i = 0; i < polygons.length; i++) {
  37445. this.plane.splitPolygon(polygons[i], front, back, front, back);
  37446. }
  37447. if (this.front) {
  37448. front = this.front.clipPolygons(front);
  37449. }
  37450. if (this.back) {
  37451. back = this.back.clipPolygons(back);
  37452. }
  37453. else {
  37454. back = [];
  37455. }
  37456. return front.concat(back);
  37457. };
  37458. // Remove all polygons in this BSP tree that are inside the other BSP tree
  37459. // `bsp`.
  37460. Node.prototype.clipTo = function (bsp) {
  37461. this.polygons = bsp.clipPolygons(this.polygons);
  37462. if (this.front)
  37463. this.front.clipTo(bsp);
  37464. if (this.back)
  37465. this.back.clipTo(bsp);
  37466. };
  37467. // Return a list of all polygons in this BSP tree.
  37468. Node.prototype.allPolygons = function () {
  37469. var polygons = this.polygons.slice();
  37470. if (this.front)
  37471. polygons = polygons.concat(this.front.allPolygons());
  37472. if (this.back)
  37473. polygons = polygons.concat(this.back.allPolygons());
  37474. return polygons;
  37475. };
  37476. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  37477. // new polygons are filtered down to the bottom of the tree and become new
  37478. // nodes there. Each set of polygons is partitioned using the first polygon
  37479. // (no heuristic is used to pick a good split).
  37480. Node.prototype.build = function (polygons) {
  37481. if (!polygons.length)
  37482. return;
  37483. if (!this.plane)
  37484. this.plane = polygons[0].plane.clone();
  37485. var front = [], back = [];
  37486. for (var i = 0; i < polygons.length; i++) {
  37487. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  37488. }
  37489. if (front.length) {
  37490. if (!this.front)
  37491. this.front = new Node();
  37492. this.front.build(front);
  37493. }
  37494. if (back.length) {
  37495. if (!this.back)
  37496. this.back = new Node();
  37497. this.back.build(back);
  37498. }
  37499. };
  37500. return Node;
  37501. })();
  37502. var CSG = (function () {
  37503. function CSG() {
  37504. this.polygons = new Array();
  37505. }
  37506. // Convert BABYLON.Mesh to BABYLON.CSG
  37507. CSG.FromMesh = function (mesh) {
  37508. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  37509. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  37510. if (mesh instanceof BABYLON.Mesh) {
  37511. mesh.computeWorldMatrix(true);
  37512. matrix = mesh.getWorldMatrix();
  37513. meshPosition = mesh.position.clone();
  37514. meshRotation = mesh.rotation.clone();
  37515. if (mesh.rotationQuaternion) {
  37516. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  37517. }
  37518. meshScaling = mesh.scaling.clone();
  37519. }
  37520. else {
  37521. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  37522. }
  37523. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37524. var subMeshes = mesh.subMeshes;
  37525. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  37526. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  37527. vertices = [];
  37528. for (var j = 0; j < 3; j++) {
  37529. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  37530. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  37531. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  37532. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  37533. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  37534. vertex = new Vertex(position, normal, uv);
  37535. vertices.push(vertex);
  37536. }
  37537. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  37538. // To handle the case of degenerated triangle
  37539. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  37540. if (polygon.plane)
  37541. polygons.push(polygon);
  37542. }
  37543. }
  37544. var csg = CSG.FromPolygons(polygons);
  37545. csg.matrix = matrix;
  37546. csg.position = meshPosition;
  37547. csg.rotation = meshRotation;
  37548. csg.scaling = meshScaling;
  37549. csg.rotationQuaternion = meshRotationQuaternion;
  37550. currentCSGMeshId++;
  37551. return csg;
  37552. };
  37553. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  37554. CSG.FromPolygons = function (polygons) {
  37555. var csg = new CSG();
  37556. csg.polygons = polygons;
  37557. return csg;
  37558. };
  37559. CSG.prototype.clone = function () {
  37560. var csg = new CSG();
  37561. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  37562. csg.copyTransformAttributes(this);
  37563. return csg;
  37564. };
  37565. CSG.prototype.toPolygons = function () {
  37566. return this.polygons;
  37567. };
  37568. CSG.prototype.union = function (csg) {
  37569. var a = new Node(this.clone().polygons);
  37570. var b = new Node(csg.clone().polygons);
  37571. a.clipTo(b);
  37572. b.clipTo(a);
  37573. b.invert();
  37574. b.clipTo(a);
  37575. b.invert();
  37576. a.build(b.allPolygons());
  37577. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37578. };
  37579. CSG.prototype.unionInPlace = function (csg) {
  37580. var a = new Node(this.polygons);
  37581. var b = new Node(csg.polygons);
  37582. a.clipTo(b);
  37583. b.clipTo(a);
  37584. b.invert();
  37585. b.clipTo(a);
  37586. b.invert();
  37587. a.build(b.allPolygons());
  37588. this.polygons = a.allPolygons();
  37589. };
  37590. CSG.prototype.subtract = function (csg) {
  37591. var a = new Node(this.clone().polygons);
  37592. var b = new Node(csg.clone().polygons);
  37593. a.invert();
  37594. a.clipTo(b);
  37595. b.clipTo(a);
  37596. b.invert();
  37597. b.clipTo(a);
  37598. b.invert();
  37599. a.build(b.allPolygons());
  37600. a.invert();
  37601. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37602. };
  37603. CSG.prototype.subtractInPlace = function (csg) {
  37604. var a = new Node(this.polygons);
  37605. var b = new Node(csg.polygons);
  37606. a.invert();
  37607. a.clipTo(b);
  37608. b.clipTo(a);
  37609. b.invert();
  37610. b.clipTo(a);
  37611. b.invert();
  37612. a.build(b.allPolygons());
  37613. a.invert();
  37614. this.polygons = a.allPolygons();
  37615. };
  37616. CSG.prototype.intersect = function (csg) {
  37617. var a = new Node(this.clone().polygons);
  37618. var b = new Node(csg.clone().polygons);
  37619. a.invert();
  37620. b.clipTo(a);
  37621. b.invert();
  37622. a.clipTo(b);
  37623. b.clipTo(a);
  37624. a.build(b.allPolygons());
  37625. a.invert();
  37626. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  37627. };
  37628. CSG.prototype.intersectInPlace = function (csg) {
  37629. var a = new Node(this.polygons);
  37630. var b = new Node(csg.polygons);
  37631. a.invert();
  37632. b.clipTo(a);
  37633. b.invert();
  37634. a.clipTo(b);
  37635. b.clipTo(a);
  37636. a.build(b.allPolygons());
  37637. a.invert();
  37638. this.polygons = a.allPolygons();
  37639. };
  37640. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  37641. // not modified.
  37642. CSG.prototype.inverse = function () {
  37643. var csg = this.clone();
  37644. csg.inverseInPlace();
  37645. return csg;
  37646. };
  37647. CSG.prototype.inverseInPlace = function () {
  37648. this.polygons.map(function (p) { p.flip(); });
  37649. };
  37650. // This is used to keep meshes transformations so they can be restored
  37651. // when we build back a Babylon Mesh
  37652. // NB : All CSG operations are performed in world coordinates
  37653. CSG.prototype.copyTransformAttributes = function (csg) {
  37654. this.matrix = csg.matrix;
  37655. this.position = csg.position;
  37656. this.rotation = csg.rotation;
  37657. this.scaling = csg.scaling;
  37658. this.rotationQuaternion = csg.rotationQuaternion;
  37659. return this;
  37660. };
  37661. // Build Raw mesh from CSG
  37662. // Coordinates here are in world space
  37663. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  37664. var matrix = this.matrix.clone();
  37665. matrix.invert();
  37666. 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;
  37667. if (keepSubMeshes) {
  37668. // Sort Polygons, since subMeshes are indices range
  37669. polygons.sort(function (a, b) {
  37670. if (a.shared.meshId === b.shared.meshId) {
  37671. return a.shared.subMeshId - b.shared.subMeshId;
  37672. }
  37673. else {
  37674. return a.shared.meshId - b.shared.meshId;
  37675. }
  37676. });
  37677. }
  37678. for (var i = 0, il = polygons.length; i < il; i++) {
  37679. polygon = polygons[i];
  37680. // Building SubMeshes
  37681. if (!subMesh_dict[polygon.shared.meshId]) {
  37682. subMesh_dict[polygon.shared.meshId] = {};
  37683. }
  37684. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  37685. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  37686. indexStart: +Infinity,
  37687. indexEnd: -Infinity,
  37688. materialIndex: polygon.shared.materialIndex
  37689. };
  37690. }
  37691. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  37692. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  37693. polygonIndices[0] = 0;
  37694. polygonIndices[1] = j - 1;
  37695. polygonIndices[2] = j;
  37696. for (var k = 0; k < 3; k++) {
  37697. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  37698. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  37699. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  37700. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  37701. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  37702. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  37703. // Check if 2 points can be merged
  37704. if (!(typeof vertex_idx !== 'undefined' &&
  37705. normals[vertex_idx * 3] === localNormal.x &&
  37706. normals[vertex_idx * 3 + 1] === localNormal.y &&
  37707. normals[vertex_idx * 3 + 2] === localNormal.z &&
  37708. uvs[vertex_idx * 2] === uv.x &&
  37709. uvs[vertex_idx * 2 + 1] === uv.y)) {
  37710. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  37711. uvs.push(uv.x, uv.y);
  37712. normals.push(normal.x, normal.y, normal.z);
  37713. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  37714. }
  37715. indices.push(vertex_idx);
  37716. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  37717. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  37718. currentIndex++;
  37719. }
  37720. }
  37721. }
  37722. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  37723. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  37724. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  37725. mesh.setIndices(indices);
  37726. if (keepSubMeshes) {
  37727. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  37728. var materialIndexOffset = 0, materialMaxIndex;
  37729. mesh.subMeshes = new Array();
  37730. for (var m in subMesh_dict) {
  37731. materialMaxIndex = -1;
  37732. for (var sm in subMesh_dict[m]) {
  37733. subMesh_obj = subMesh_dict[m][sm];
  37734. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  37735. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  37736. }
  37737. materialIndexOffset += ++materialMaxIndex;
  37738. }
  37739. }
  37740. return mesh;
  37741. };
  37742. // Build Mesh from CSG taking material and transforms into account
  37743. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  37744. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  37745. mesh.material = material;
  37746. mesh.position.copyFrom(this.position);
  37747. mesh.rotation.copyFrom(this.rotation);
  37748. if (this.rotationQuaternion) {
  37749. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  37750. }
  37751. mesh.scaling.copyFrom(this.scaling);
  37752. mesh.computeWorldMatrix(true);
  37753. return mesh;
  37754. };
  37755. return CSG;
  37756. })();
  37757. BABYLON.CSG = CSG;
  37758. })(BABYLON || (BABYLON = {}));
  37759. var BABYLON;
  37760. (function (BABYLON) {
  37761. var VRDistortionCorrectionPostProcess = (function (_super) {
  37762. __extends(VRDistortionCorrectionPostProcess, _super);
  37763. //ANY
  37764. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  37765. var _this = this;
  37766. _super.call(this, name, "vrDistortionCorrection", [
  37767. 'LensCenter',
  37768. 'Scale',
  37769. 'ScaleIn',
  37770. 'HmdWarpParam'
  37771. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  37772. this._isRightEye = isRightEye;
  37773. this._distortionFactors = vrMetrics.distortionK;
  37774. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  37775. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  37776. this.onSizeChanged = function () {
  37777. _this.aspectRatio = _this.width * .5 / _this.height;
  37778. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  37779. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  37780. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  37781. };
  37782. this.onApply = function (effect) {
  37783. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  37784. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  37785. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  37786. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  37787. };
  37788. }
  37789. return VRDistortionCorrectionPostProcess;
  37790. })(BABYLON.PostProcess);
  37791. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  37792. })(BABYLON || (BABYLON = {}));
  37793. // Mainly based on these 2 articles :
  37794. // 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
  37795. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  37796. var BABYLON;
  37797. (function (BABYLON) {
  37798. (function (JoystickAxis) {
  37799. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  37800. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  37801. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  37802. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  37803. var JoystickAxis = BABYLON.JoystickAxis;
  37804. var VirtualJoystick = (function () {
  37805. function VirtualJoystick(leftJoystick) {
  37806. var _this = this;
  37807. if (leftJoystick) {
  37808. this._leftJoystick = true;
  37809. }
  37810. else {
  37811. this._leftJoystick = false;
  37812. }
  37813. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  37814. VirtualJoystick._globalJoystickIndex++;
  37815. // By default left & right arrow keys are moving the X
  37816. // and up & down keys are moving the Y
  37817. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  37818. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  37819. this.reverseLeftRight = false;
  37820. this.reverseUpDown = false;
  37821. // collections of pointers
  37822. this._touches = new BABYLON.StringDictionary();
  37823. this.deltaPosition = BABYLON.Vector3.Zero();
  37824. this._joystickSensibility = 25;
  37825. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  37826. this._rotationSpeed = 25;
  37827. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  37828. this._rotateOnAxisRelativeToMesh = false;
  37829. this._onResize = function (evt) {
  37830. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  37831. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  37832. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  37833. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  37834. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  37835. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  37836. };
  37837. // injecting a canvas element on top of the canvas 3D game
  37838. if (!VirtualJoystick.vjCanvas) {
  37839. window.addEventListener("resize", this._onResize, false);
  37840. VirtualJoystick.vjCanvas = document.createElement("canvas");
  37841. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  37842. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  37843. VirtualJoystick.vjCanvas.width = window.innerWidth;
  37844. VirtualJoystick.vjCanvas.height = window.innerHeight;
  37845. VirtualJoystick.vjCanvas.style.width = "100%";
  37846. VirtualJoystick.vjCanvas.style.height = "100%";
  37847. VirtualJoystick.vjCanvas.style.position = "absolute";
  37848. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  37849. VirtualJoystick.vjCanvas.style.top = "0px";
  37850. VirtualJoystick.vjCanvas.style.left = "0px";
  37851. VirtualJoystick.vjCanvas.style.zIndex = "5";
  37852. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  37853. // Support for jQuery PEP polyfill
  37854. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  37855. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  37856. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  37857. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  37858. document.body.appendChild(VirtualJoystick.vjCanvas);
  37859. }
  37860. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  37861. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  37862. this.pressed = false;
  37863. // default joystick color
  37864. this._joystickColor = "cyan";
  37865. this._joystickPointerID = -1;
  37866. // current joystick position
  37867. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  37868. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  37869. // origin joystick position
  37870. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  37871. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  37872. this._onPointerDownHandlerRef = function (evt) {
  37873. _this._onPointerDown(evt);
  37874. };
  37875. this._onPointerMoveHandlerRef = function (evt) {
  37876. _this._onPointerMove(evt);
  37877. };
  37878. this._onPointerOutHandlerRef = function (evt) {
  37879. _this._onPointerUp(evt);
  37880. };
  37881. this._onPointerUpHandlerRef = function (evt) {
  37882. _this._onPointerUp(evt);
  37883. };
  37884. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  37885. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  37886. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  37887. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  37888. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  37889. evt.preventDefault(); // Disables system menu
  37890. }, false);
  37891. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  37892. }
  37893. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  37894. this._joystickSensibility = newJoystickSensibility;
  37895. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  37896. };
  37897. VirtualJoystick.prototype._onPointerDown = function (e) {
  37898. var positionOnScreenCondition;
  37899. e.preventDefault();
  37900. if (this._leftJoystick === true) {
  37901. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  37902. }
  37903. else {
  37904. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  37905. }
  37906. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  37907. // First contact will be dedicated to the virtual joystick
  37908. this._joystickPointerID = e.pointerId;
  37909. this._joystickPointerStartPos.x = e.clientX;
  37910. this._joystickPointerStartPos.y = e.clientY;
  37911. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  37912. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  37913. this._deltaJoystickVector.x = 0;
  37914. this._deltaJoystickVector.y = 0;
  37915. this.pressed = true;
  37916. this._touches.add(e.pointerId.toString(), e);
  37917. }
  37918. else {
  37919. // You can only trigger the action buttons with a joystick declared
  37920. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  37921. this._action();
  37922. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  37923. }
  37924. }
  37925. };
  37926. VirtualJoystick.prototype._onPointerMove = function (e) {
  37927. // If the current pointer is the one associated to the joystick (first touch contact)
  37928. if (this._joystickPointerID == e.pointerId) {
  37929. this._joystickPointerPos.x = e.clientX;
  37930. this._joystickPointerPos.y = e.clientY;
  37931. this._deltaJoystickVector = this._joystickPointerPos.clone();
  37932. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  37933. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  37934. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  37935. switch (this._axisTargetedByLeftAndRight) {
  37936. case JoystickAxis.X:
  37937. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  37938. break;
  37939. case JoystickAxis.Y:
  37940. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  37941. break;
  37942. case JoystickAxis.Z:
  37943. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  37944. break;
  37945. }
  37946. var directionUpDown = this.reverseUpDown ? 1 : -1;
  37947. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  37948. switch (this._axisTargetedByUpAndDown) {
  37949. case JoystickAxis.X:
  37950. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  37951. break;
  37952. case JoystickAxis.Y:
  37953. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  37954. break;
  37955. case JoystickAxis.Z:
  37956. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  37957. break;
  37958. }
  37959. }
  37960. else {
  37961. var data = this._touches.get(e.pointerId.toString());
  37962. if (data) {
  37963. data.x = e.clientX;
  37964. data.y = e.clientY;
  37965. }
  37966. }
  37967. };
  37968. VirtualJoystick.prototype._onPointerUp = function (e) {
  37969. if (this._joystickPointerID == e.pointerId) {
  37970. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  37971. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  37972. this._joystickPointerID = -1;
  37973. this.pressed = false;
  37974. }
  37975. else {
  37976. var touch = this._touches.get(e.pointerId.toString());
  37977. if (touch) {
  37978. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37979. }
  37980. }
  37981. this._deltaJoystickVector.x = 0;
  37982. this._deltaJoystickVector.y = 0;
  37983. this._touches.remove(e.pointerId.toString());
  37984. };
  37985. /**
  37986. * Change the color of the virtual joystick
  37987. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  37988. */
  37989. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  37990. this._joystickColor = newColor;
  37991. };
  37992. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  37993. this._action = action;
  37994. };
  37995. // Define which axis you'd like to control for left & right
  37996. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  37997. switch (axis) {
  37998. case JoystickAxis.X:
  37999. case JoystickAxis.Y:
  38000. case JoystickAxis.Z:
  38001. this._axisTargetedByLeftAndRight = axis;
  38002. break;
  38003. default:
  38004. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  38005. break;
  38006. }
  38007. };
  38008. // Define which axis you'd like to control for up & down
  38009. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  38010. switch (axis) {
  38011. case JoystickAxis.X:
  38012. case JoystickAxis.Y:
  38013. case JoystickAxis.Z:
  38014. this._axisTargetedByUpAndDown = axis;
  38015. break;
  38016. default:
  38017. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  38018. break;
  38019. }
  38020. };
  38021. VirtualJoystick.prototype._clearCanvas = function () {
  38022. if (this._leftJoystick) {
  38023. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  38024. }
  38025. else {
  38026. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  38027. }
  38028. };
  38029. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  38030. var _this = this;
  38031. if (this.pressed) {
  38032. this._touches.forEach(function (touch) {
  38033. if (touch.pointerId === _this._joystickPointerID) {
  38034. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  38035. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  38036. VirtualJoystick.vjCanvasContext.beginPath();
  38037. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  38038. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  38039. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  38040. VirtualJoystick.vjCanvasContext.stroke();
  38041. VirtualJoystick.vjCanvasContext.closePath();
  38042. VirtualJoystick.vjCanvasContext.beginPath();
  38043. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  38044. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  38045. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  38046. VirtualJoystick.vjCanvasContext.stroke();
  38047. VirtualJoystick.vjCanvasContext.closePath();
  38048. VirtualJoystick.vjCanvasContext.beginPath();
  38049. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  38050. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  38051. VirtualJoystick.vjCanvasContext.stroke();
  38052. VirtualJoystick.vjCanvasContext.closePath();
  38053. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  38054. }
  38055. else {
  38056. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  38057. VirtualJoystick.vjCanvasContext.beginPath();
  38058. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  38059. VirtualJoystick.vjCanvasContext.beginPath();
  38060. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  38061. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  38062. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  38063. VirtualJoystick.vjCanvasContext.stroke();
  38064. VirtualJoystick.vjCanvasContext.closePath();
  38065. touch.prevX = touch.x;
  38066. touch.prevY = touch.y;
  38067. }
  38068. ;
  38069. });
  38070. }
  38071. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  38072. };
  38073. VirtualJoystick.prototype.releaseCanvas = function () {
  38074. if (VirtualJoystick.vjCanvas) {
  38075. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  38076. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  38077. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  38078. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  38079. window.removeEventListener("resize", this._onResize);
  38080. document.body.removeChild(VirtualJoystick.vjCanvas);
  38081. VirtualJoystick.vjCanvas = null;
  38082. }
  38083. };
  38084. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  38085. VirtualJoystick._globalJoystickIndex = 0;
  38086. return VirtualJoystick;
  38087. })();
  38088. BABYLON.VirtualJoystick = VirtualJoystick;
  38089. })(BABYLON || (BABYLON = {}));
  38090. var BABYLON;
  38091. (function (BABYLON) {
  38092. // We're mainly based on the logic defined into the FreeCamera code
  38093. var VirtualJoysticksCamera = (function (_super) {
  38094. __extends(VirtualJoysticksCamera, _super);
  38095. function VirtualJoysticksCamera(name, position, scene) {
  38096. _super.call(this, name, position, scene);
  38097. this.inputs.addVirtualJoystick();
  38098. }
  38099. return VirtualJoysticksCamera;
  38100. })(BABYLON.FreeCamera);
  38101. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  38102. })(BABYLON || (BABYLON = {}));
  38103. var BABYLON;
  38104. (function (BABYLON) {
  38105. var AnaglyphPostProcess = (function (_super) {
  38106. __extends(AnaglyphPostProcess, _super);
  38107. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38108. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  38109. }
  38110. return AnaglyphPostProcess;
  38111. })(BABYLON.PostProcess);
  38112. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  38113. })(BABYLON || (BABYLON = {}));
  38114. var BABYLON;
  38115. (function (BABYLON) {
  38116. var OutlineRenderer = (function () {
  38117. function OutlineRenderer(scene) {
  38118. this._scene = scene;
  38119. }
  38120. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  38121. var _this = this;
  38122. if (useOverlay === void 0) { useOverlay = false; }
  38123. var scene = this._scene;
  38124. var engine = this._scene.getEngine();
  38125. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38126. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  38127. return;
  38128. }
  38129. var mesh = subMesh.getRenderingMesh();
  38130. var material = subMesh.getMaterial();
  38131. engine.enableEffect(this._effect);
  38132. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  38133. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  38134. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  38135. // Bones
  38136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38137. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38138. }
  38139. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  38140. // Alpha test
  38141. if (material && material.needAlphaTesting()) {
  38142. var alphaTexture = material.getAlphaTestTexture();
  38143. this._effect.setTexture("diffuseSampler", alphaTexture);
  38144. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38145. }
  38146. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  38147. };
  38148. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  38149. var defines = [];
  38150. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  38151. var mesh = subMesh.getMesh();
  38152. var material = subMesh.getMaterial();
  38153. // Alpha test
  38154. if (material && material.needAlphaTesting()) {
  38155. defines.push("#define ALPHATEST");
  38156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38157. attribs.push(BABYLON.VertexBuffer.UVKind);
  38158. defines.push("#define UV1");
  38159. }
  38160. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38161. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38162. defines.push("#define UV2");
  38163. }
  38164. }
  38165. // Bones
  38166. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38167. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38168. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38169. if (mesh.numBoneInfluencers > 4) {
  38170. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38171. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38172. }
  38173. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38174. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38175. }
  38176. else {
  38177. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38178. }
  38179. // Instances
  38180. if (useInstances) {
  38181. defines.push("#define INSTANCES");
  38182. attribs.push("world0");
  38183. attribs.push("world1");
  38184. attribs.push("world2");
  38185. attribs.push("world3");
  38186. }
  38187. // Get correct effect
  38188. var join = defines.join("\n");
  38189. if (this._cachedDefines !== join) {
  38190. this._cachedDefines = join;
  38191. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  38192. }
  38193. return this._effect.isReady();
  38194. };
  38195. return OutlineRenderer;
  38196. })();
  38197. BABYLON.OutlineRenderer = OutlineRenderer;
  38198. })(BABYLON || (BABYLON = {}));
  38199. var BABYLON;
  38200. (function (BABYLON) {
  38201. var MeshAssetTask = (function () {
  38202. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  38203. this.name = name;
  38204. this.meshesNames = meshesNames;
  38205. this.rootUrl = rootUrl;
  38206. this.sceneFilename = sceneFilename;
  38207. this.isCompleted = false;
  38208. }
  38209. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38210. var _this = this;
  38211. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  38212. _this.loadedMeshes = meshes;
  38213. _this.loadedParticleSystems = particleSystems;
  38214. _this.loadedSkeletons = skeletons;
  38215. _this.isCompleted = true;
  38216. if (_this.onSuccess) {
  38217. _this.onSuccess(_this);
  38218. }
  38219. onSuccess();
  38220. }, null, function () {
  38221. if (_this.onError) {
  38222. _this.onError(_this);
  38223. }
  38224. onError();
  38225. });
  38226. };
  38227. return MeshAssetTask;
  38228. })();
  38229. BABYLON.MeshAssetTask = MeshAssetTask;
  38230. var TextFileAssetTask = (function () {
  38231. function TextFileAssetTask(name, url) {
  38232. this.name = name;
  38233. this.url = url;
  38234. this.isCompleted = false;
  38235. }
  38236. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38237. var _this = this;
  38238. BABYLON.Tools.LoadFile(this.url, function (data) {
  38239. _this.text = data;
  38240. _this.isCompleted = true;
  38241. if (_this.onSuccess) {
  38242. _this.onSuccess(_this);
  38243. }
  38244. onSuccess();
  38245. }, null, scene.database, false, function () {
  38246. if (_this.onError) {
  38247. _this.onError(_this);
  38248. }
  38249. onError();
  38250. });
  38251. };
  38252. return TextFileAssetTask;
  38253. })();
  38254. BABYLON.TextFileAssetTask = TextFileAssetTask;
  38255. var BinaryFileAssetTask = (function () {
  38256. function BinaryFileAssetTask(name, url) {
  38257. this.name = name;
  38258. this.url = url;
  38259. this.isCompleted = false;
  38260. }
  38261. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38262. var _this = this;
  38263. BABYLON.Tools.LoadFile(this.url, function (data) {
  38264. _this.data = data;
  38265. _this.isCompleted = true;
  38266. if (_this.onSuccess) {
  38267. _this.onSuccess(_this);
  38268. }
  38269. onSuccess();
  38270. }, null, scene.database, true, function () {
  38271. if (_this.onError) {
  38272. _this.onError(_this);
  38273. }
  38274. onError();
  38275. });
  38276. };
  38277. return BinaryFileAssetTask;
  38278. })();
  38279. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  38280. var ImageAssetTask = (function () {
  38281. function ImageAssetTask(name, url) {
  38282. this.name = name;
  38283. this.url = url;
  38284. this.isCompleted = false;
  38285. }
  38286. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38287. var _this = this;
  38288. var img = new Image();
  38289. img.onload = function () {
  38290. _this.image = img;
  38291. _this.isCompleted = true;
  38292. if (_this.onSuccess) {
  38293. _this.onSuccess(_this);
  38294. }
  38295. onSuccess();
  38296. };
  38297. img.onerror = function () {
  38298. if (_this.onError) {
  38299. _this.onError(_this);
  38300. }
  38301. onError();
  38302. };
  38303. img.src = this.url;
  38304. };
  38305. return ImageAssetTask;
  38306. })();
  38307. BABYLON.ImageAssetTask = ImageAssetTask;
  38308. var TextureAssetTask = (function () {
  38309. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  38310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38311. this.name = name;
  38312. this.url = url;
  38313. this.noMipmap = noMipmap;
  38314. this.invertY = invertY;
  38315. this.samplingMode = samplingMode;
  38316. this.isCompleted = false;
  38317. }
  38318. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  38319. var _this = this;
  38320. var onload = function () {
  38321. _this.isCompleted = true;
  38322. if (_this.onSuccess) {
  38323. _this.onSuccess(_this);
  38324. }
  38325. onSuccess();
  38326. };
  38327. var onerror = function () {
  38328. if (_this.onError) {
  38329. _this.onError(_this);
  38330. }
  38331. onError();
  38332. };
  38333. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  38334. };
  38335. return TextureAssetTask;
  38336. })();
  38337. BABYLON.TextureAssetTask = TextureAssetTask;
  38338. var AssetsManager = (function () {
  38339. function AssetsManager(scene) {
  38340. this._tasks = new Array();
  38341. this._waitingTasksCount = 0;
  38342. this.useDefaultLoadingScreen = true;
  38343. this._scene = scene;
  38344. }
  38345. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  38346. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  38347. this._tasks.push(task);
  38348. return task;
  38349. };
  38350. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  38351. var task = new TextFileAssetTask(taskName, url);
  38352. this._tasks.push(task);
  38353. return task;
  38354. };
  38355. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  38356. var task = new BinaryFileAssetTask(taskName, url);
  38357. this._tasks.push(task);
  38358. return task;
  38359. };
  38360. AssetsManager.prototype.addImageTask = function (taskName, url) {
  38361. var task = new ImageAssetTask(taskName, url);
  38362. this._tasks.push(task);
  38363. return task;
  38364. };
  38365. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  38366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38367. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  38368. this._tasks.push(task);
  38369. return task;
  38370. };
  38371. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  38372. this._waitingTasksCount--;
  38373. if (this._waitingTasksCount === 0) {
  38374. if (this.onFinish) {
  38375. this.onFinish(this._tasks);
  38376. }
  38377. this._scene.getEngine().hideLoadingUI();
  38378. }
  38379. };
  38380. AssetsManager.prototype._runTask = function (task) {
  38381. var _this = this;
  38382. task.run(this._scene, function () {
  38383. if (_this.onTaskSuccess) {
  38384. _this.onTaskSuccess(task);
  38385. }
  38386. _this._decreaseWaitingTasksCount();
  38387. }, function () {
  38388. if (_this.onTaskError) {
  38389. _this.onTaskError(task);
  38390. }
  38391. _this._decreaseWaitingTasksCount();
  38392. });
  38393. };
  38394. AssetsManager.prototype.reset = function () {
  38395. this._tasks = new Array();
  38396. return this;
  38397. };
  38398. AssetsManager.prototype.load = function () {
  38399. this._waitingTasksCount = this._tasks.length;
  38400. if (this._waitingTasksCount === 0) {
  38401. if (this.onFinish) {
  38402. this.onFinish(this._tasks);
  38403. }
  38404. return this;
  38405. }
  38406. if (this.useDefaultLoadingScreen) {
  38407. this._scene.getEngine().displayLoadingUI();
  38408. }
  38409. for (var index = 0; index < this._tasks.length; index++) {
  38410. var task = this._tasks[index];
  38411. this._runTask(task);
  38412. }
  38413. return this;
  38414. };
  38415. return AssetsManager;
  38416. })();
  38417. BABYLON.AssetsManager = AssetsManager;
  38418. })(BABYLON || (BABYLON = {}));
  38419. var BABYLON;
  38420. (function (BABYLON) {
  38421. var VRCameraMetrics = (function () {
  38422. function VRCameraMetrics() {
  38423. this.compensateDistortion = true;
  38424. }
  38425. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  38426. get: function () {
  38427. return this.hResolution / (2 * this.vResolution);
  38428. },
  38429. enumerable: true,
  38430. configurable: true
  38431. });
  38432. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  38433. get: function () {
  38434. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  38435. },
  38436. enumerable: true,
  38437. configurable: true
  38438. });
  38439. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  38440. get: function () {
  38441. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  38442. var h = (4 * meters) / this.hScreenSize;
  38443. return BABYLON.Matrix.Translation(h, 0, 0);
  38444. },
  38445. enumerable: true,
  38446. configurable: true
  38447. });
  38448. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  38449. get: function () {
  38450. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  38451. var h = (4 * meters) / this.hScreenSize;
  38452. return BABYLON.Matrix.Translation(-h, 0, 0);
  38453. },
  38454. enumerable: true,
  38455. configurable: true
  38456. });
  38457. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  38458. get: function () {
  38459. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  38460. },
  38461. enumerable: true,
  38462. configurable: true
  38463. });
  38464. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  38465. get: function () {
  38466. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  38467. },
  38468. enumerable: true,
  38469. configurable: true
  38470. });
  38471. VRCameraMetrics.GetDefault = function () {
  38472. var result = new VRCameraMetrics();
  38473. result.hResolution = 1280;
  38474. result.vResolution = 800;
  38475. result.hScreenSize = 0.149759993;
  38476. result.vScreenSize = 0.0935999975;
  38477. result.vScreenCenter = 0.0467999987,
  38478. result.eyeToScreenDistance = 0.0410000011;
  38479. result.lensSeparationDistance = 0.0635000020;
  38480. result.interpupillaryDistance = 0.0640000030;
  38481. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  38482. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  38483. result.postProcessScaleFactor = 1.714605507808412;
  38484. result.lensCenterOffset = 0.151976421;
  38485. return result;
  38486. };
  38487. return VRCameraMetrics;
  38488. })();
  38489. BABYLON.VRCameraMetrics = VRCameraMetrics;
  38490. })(BABYLON || (BABYLON = {}));
  38491. var BABYLON;
  38492. (function (BABYLON) {
  38493. var VRDeviceOrientationFreeCamera = (function (_super) {
  38494. __extends(VRDeviceOrientationFreeCamera, _super);
  38495. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  38496. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38497. _super.call(this, name, position, scene);
  38498. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38499. metrics.compensateDistortion = compensateDistortion;
  38500. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38501. this.inputs.addVRDeviceOrientation();
  38502. }
  38503. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  38504. return "VRDeviceOrientationFreeCamera";
  38505. };
  38506. return VRDeviceOrientationFreeCamera;
  38507. })(BABYLON.FreeCamera);
  38508. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  38509. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  38510. __extends(VRDeviceOrientationArcRotateCamera, _super);
  38511. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  38512. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38513. _super.call(this, name, alpha, beta, radius, target, scene);
  38514. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38515. metrics.compensateDistortion = compensateDistortion;
  38516. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38517. this.inputs.addVRDeviceOrientation();
  38518. }
  38519. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  38520. return "VRDeviceOrientationArcRotateCamera";
  38521. };
  38522. return VRDeviceOrientationArcRotateCamera;
  38523. })(BABYLON.ArcRotateCamera);
  38524. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  38525. })(BABYLON || (BABYLON = {}));
  38526. var BABYLON;
  38527. (function (BABYLON) {
  38528. var WebVRFreeCamera = (function (_super) {
  38529. __extends(WebVRFreeCamera, _super);
  38530. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  38531. if (compensateDistortion === void 0) { compensateDistortion = true; }
  38532. _super.call(this, name, position, scene);
  38533. this._hmdDevice = null;
  38534. this._sensorDevice = null;
  38535. this._cacheState = null;
  38536. this._cacheQuaternion = new BABYLON.Quaternion();
  38537. this._cacheRotation = BABYLON.Vector3.Zero();
  38538. this._vrEnabled = false;
  38539. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  38540. metrics.compensateDistortion = compensateDistortion;
  38541. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  38542. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  38543. }
  38544. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  38545. var size = devices.length;
  38546. var i = 0;
  38547. // Reset devices.
  38548. this._sensorDevice = null;
  38549. this._hmdDevice = null;
  38550. // Search for a HmdDevice.
  38551. while (i < size && this._hmdDevice === null) {
  38552. if (devices[i] instanceof HMDVRDevice) {
  38553. this._hmdDevice = devices[i];
  38554. }
  38555. i++;
  38556. }
  38557. i = 0;
  38558. while (i < size && this._sensorDevice === null) {
  38559. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  38560. this._sensorDevice = devices[i];
  38561. }
  38562. i++;
  38563. }
  38564. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  38565. };
  38566. WebVRFreeCamera.prototype._checkInputs = function () {
  38567. if (this._vrEnabled) {
  38568. this._cacheState = this._sensorDevice.getState();
  38569. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  38570. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  38571. this.rotation.x = -this._cacheRotation.x;
  38572. this.rotation.y = -this._cacheRotation.y;
  38573. this.rotation.z = this._cacheRotation.z;
  38574. }
  38575. _super.prototype._checkInputs.call(this);
  38576. };
  38577. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38578. _super.prototype.attachControl.call(this, element, noPreventDefault);
  38579. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38580. if (navigator.getVRDevices) {
  38581. navigator.getVRDevices().then(this._getWebVRDevices);
  38582. }
  38583. else if (navigator.mozGetVRDevices) {
  38584. navigator.mozGetVRDevices(this._getWebVRDevices);
  38585. }
  38586. };
  38587. WebVRFreeCamera.prototype.detachControl = function (element) {
  38588. _super.prototype.detachControl.call(this, element);
  38589. this._vrEnabled = false;
  38590. };
  38591. WebVRFreeCamera.prototype.getTypeName = function () {
  38592. return "WebVRFreeCamera";
  38593. };
  38594. return WebVRFreeCamera;
  38595. })(BABYLON.FreeCamera);
  38596. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  38597. })(BABYLON || (BABYLON = {}));
  38598. var BABYLON;
  38599. (function (BABYLON) {
  38600. // Standard optimizations
  38601. var SceneOptimization = (function () {
  38602. function SceneOptimization(priority) {
  38603. if (priority === void 0) { priority = 0; }
  38604. this.priority = priority;
  38605. this.apply = function (scene) {
  38606. return true; // Return true if everything that can be done was applied
  38607. };
  38608. }
  38609. return SceneOptimization;
  38610. })();
  38611. BABYLON.SceneOptimization = SceneOptimization;
  38612. var TextureOptimization = (function (_super) {
  38613. __extends(TextureOptimization, _super);
  38614. function TextureOptimization(priority, maximumSize) {
  38615. var _this = this;
  38616. if (priority === void 0) { priority = 0; }
  38617. if (maximumSize === void 0) { maximumSize = 1024; }
  38618. _super.call(this, priority);
  38619. this.priority = priority;
  38620. this.maximumSize = maximumSize;
  38621. this.apply = function (scene) {
  38622. var allDone = true;
  38623. for (var index = 0; index < scene.textures.length; index++) {
  38624. var texture = scene.textures[index];
  38625. if (!texture.canRescale) {
  38626. continue;
  38627. }
  38628. var currentSize = texture.getSize();
  38629. var maxDimension = Math.max(currentSize.width, currentSize.height);
  38630. if (maxDimension > _this.maximumSize) {
  38631. texture.scale(0.5);
  38632. allDone = false;
  38633. }
  38634. }
  38635. return allDone;
  38636. };
  38637. }
  38638. return TextureOptimization;
  38639. })(SceneOptimization);
  38640. BABYLON.TextureOptimization = TextureOptimization;
  38641. var HardwareScalingOptimization = (function (_super) {
  38642. __extends(HardwareScalingOptimization, _super);
  38643. function HardwareScalingOptimization(priority, maximumScale) {
  38644. var _this = this;
  38645. if (priority === void 0) { priority = 0; }
  38646. if (maximumScale === void 0) { maximumScale = 2; }
  38647. _super.call(this, priority);
  38648. this.priority = priority;
  38649. this.maximumScale = maximumScale;
  38650. this._currentScale = 1;
  38651. this.apply = function (scene) {
  38652. _this._currentScale++;
  38653. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  38654. return _this._currentScale >= _this.maximumScale;
  38655. };
  38656. }
  38657. return HardwareScalingOptimization;
  38658. })(SceneOptimization);
  38659. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  38660. var ShadowsOptimization = (function (_super) {
  38661. __extends(ShadowsOptimization, _super);
  38662. function ShadowsOptimization() {
  38663. _super.apply(this, arguments);
  38664. this.apply = function (scene) {
  38665. scene.shadowsEnabled = false;
  38666. return true;
  38667. };
  38668. }
  38669. return ShadowsOptimization;
  38670. })(SceneOptimization);
  38671. BABYLON.ShadowsOptimization = ShadowsOptimization;
  38672. var PostProcessesOptimization = (function (_super) {
  38673. __extends(PostProcessesOptimization, _super);
  38674. function PostProcessesOptimization() {
  38675. _super.apply(this, arguments);
  38676. this.apply = function (scene) {
  38677. scene.postProcessesEnabled = false;
  38678. return true;
  38679. };
  38680. }
  38681. return PostProcessesOptimization;
  38682. })(SceneOptimization);
  38683. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  38684. var LensFlaresOptimization = (function (_super) {
  38685. __extends(LensFlaresOptimization, _super);
  38686. function LensFlaresOptimization() {
  38687. _super.apply(this, arguments);
  38688. this.apply = function (scene) {
  38689. scene.lensFlaresEnabled = false;
  38690. return true;
  38691. };
  38692. }
  38693. return LensFlaresOptimization;
  38694. })(SceneOptimization);
  38695. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  38696. var ParticlesOptimization = (function (_super) {
  38697. __extends(ParticlesOptimization, _super);
  38698. function ParticlesOptimization() {
  38699. _super.apply(this, arguments);
  38700. this.apply = function (scene) {
  38701. scene.particlesEnabled = false;
  38702. return true;
  38703. };
  38704. }
  38705. return ParticlesOptimization;
  38706. })(SceneOptimization);
  38707. BABYLON.ParticlesOptimization = ParticlesOptimization;
  38708. var RenderTargetsOptimization = (function (_super) {
  38709. __extends(RenderTargetsOptimization, _super);
  38710. function RenderTargetsOptimization() {
  38711. _super.apply(this, arguments);
  38712. this.apply = function (scene) {
  38713. scene.renderTargetsEnabled = false;
  38714. return true;
  38715. };
  38716. }
  38717. return RenderTargetsOptimization;
  38718. })(SceneOptimization);
  38719. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  38720. var MergeMeshesOptimization = (function (_super) {
  38721. __extends(MergeMeshesOptimization, _super);
  38722. function MergeMeshesOptimization() {
  38723. var _this = this;
  38724. _super.apply(this, arguments);
  38725. this._canBeMerged = function (abstractMesh) {
  38726. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  38727. return false;
  38728. }
  38729. var mesh = abstractMesh;
  38730. if (!mesh.isVisible || !mesh.isEnabled()) {
  38731. return false;
  38732. }
  38733. if (mesh.instances.length > 0) {
  38734. return false;
  38735. }
  38736. if (mesh.skeleton || mesh.hasLODLevels) {
  38737. return false;
  38738. }
  38739. if (mesh.parent) {
  38740. return false;
  38741. }
  38742. return true;
  38743. };
  38744. this.apply = function (scene, updateSelectionTree) {
  38745. var globalPool = scene.meshes.slice(0);
  38746. var globalLength = globalPool.length;
  38747. for (var index = 0; index < globalLength; index++) {
  38748. var currentPool = new Array();
  38749. var current = globalPool[index];
  38750. // Checks
  38751. if (!_this._canBeMerged(current)) {
  38752. continue;
  38753. }
  38754. currentPool.push(current);
  38755. // Find compatible meshes
  38756. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  38757. var otherMesh = globalPool[subIndex];
  38758. if (!_this._canBeMerged(otherMesh)) {
  38759. continue;
  38760. }
  38761. if (otherMesh.material !== current.material) {
  38762. continue;
  38763. }
  38764. if (otherMesh.checkCollisions !== current.checkCollisions) {
  38765. continue;
  38766. }
  38767. currentPool.push(otherMesh);
  38768. globalLength--;
  38769. globalPool.splice(subIndex, 1);
  38770. subIndex--;
  38771. }
  38772. if (currentPool.length < 2) {
  38773. continue;
  38774. }
  38775. // Merge meshes
  38776. BABYLON.Mesh.MergeMeshes(currentPool);
  38777. }
  38778. if (updateSelectionTree != undefined) {
  38779. if (updateSelectionTree) {
  38780. scene.createOrUpdateSelectionOctree();
  38781. }
  38782. }
  38783. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  38784. scene.createOrUpdateSelectionOctree();
  38785. }
  38786. return true;
  38787. };
  38788. }
  38789. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  38790. get: function () {
  38791. return MergeMeshesOptimization._UpdateSelectionTree;
  38792. },
  38793. set: function (value) {
  38794. MergeMeshesOptimization._UpdateSelectionTree = value;
  38795. },
  38796. enumerable: true,
  38797. configurable: true
  38798. });
  38799. MergeMeshesOptimization._UpdateSelectionTree = false;
  38800. return MergeMeshesOptimization;
  38801. })(SceneOptimization);
  38802. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  38803. // Options
  38804. var SceneOptimizerOptions = (function () {
  38805. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  38806. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  38807. if (trackerDuration === void 0) { trackerDuration = 2000; }
  38808. this.targetFrameRate = targetFrameRate;
  38809. this.trackerDuration = trackerDuration;
  38810. this.optimizations = new Array();
  38811. }
  38812. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  38813. var result = new SceneOptimizerOptions(targetFrameRate);
  38814. var priority = 0;
  38815. result.optimizations.push(new MergeMeshesOptimization(priority));
  38816. result.optimizations.push(new ShadowsOptimization(priority));
  38817. result.optimizations.push(new LensFlaresOptimization(priority));
  38818. // Next priority
  38819. priority++;
  38820. result.optimizations.push(new PostProcessesOptimization(priority));
  38821. result.optimizations.push(new ParticlesOptimization(priority));
  38822. // Next priority
  38823. priority++;
  38824. result.optimizations.push(new TextureOptimization(priority, 1024));
  38825. return result;
  38826. };
  38827. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  38828. var result = new SceneOptimizerOptions(targetFrameRate);
  38829. var priority = 0;
  38830. result.optimizations.push(new MergeMeshesOptimization(priority));
  38831. result.optimizations.push(new ShadowsOptimization(priority));
  38832. result.optimizations.push(new LensFlaresOptimization(priority));
  38833. // Next priority
  38834. priority++;
  38835. result.optimizations.push(new PostProcessesOptimization(priority));
  38836. result.optimizations.push(new ParticlesOptimization(priority));
  38837. // Next priority
  38838. priority++;
  38839. result.optimizations.push(new TextureOptimization(priority, 512));
  38840. // Next priority
  38841. priority++;
  38842. result.optimizations.push(new RenderTargetsOptimization(priority));
  38843. // Next priority
  38844. priority++;
  38845. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  38846. return result;
  38847. };
  38848. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  38849. var result = new SceneOptimizerOptions(targetFrameRate);
  38850. var priority = 0;
  38851. result.optimizations.push(new MergeMeshesOptimization(priority));
  38852. result.optimizations.push(new ShadowsOptimization(priority));
  38853. result.optimizations.push(new LensFlaresOptimization(priority));
  38854. // Next priority
  38855. priority++;
  38856. result.optimizations.push(new PostProcessesOptimization(priority));
  38857. result.optimizations.push(new ParticlesOptimization(priority));
  38858. // Next priority
  38859. priority++;
  38860. result.optimizations.push(new TextureOptimization(priority, 256));
  38861. // Next priority
  38862. priority++;
  38863. result.optimizations.push(new RenderTargetsOptimization(priority));
  38864. // Next priority
  38865. priority++;
  38866. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  38867. return result;
  38868. };
  38869. return SceneOptimizerOptions;
  38870. })();
  38871. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  38872. // Scene optimizer tool
  38873. var SceneOptimizer = (function () {
  38874. function SceneOptimizer() {
  38875. }
  38876. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  38877. // TODO: add an epsilon
  38878. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  38879. if (onSuccess) {
  38880. onSuccess();
  38881. }
  38882. return;
  38883. }
  38884. // Apply current level of optimizations
  38885. var allDone = true;
  38886. var noOptimizationApplied = true;
  38887. for (var index = 0; index < options.optimizations.length; index++) {
  38888. var optimization = options.optimizations[index];
  38889. if (optimization.priority === currentPriorityLevel) {
  38890. noOptimizationApplied = false;
  38891. allDone = allDone && optimization.apply(scene);
  38892. }
  38893. }
  38894. // If no optimization was applied, this is a failure :(
  38895. if (noOptimizationApplied) {
  38896. if (onFailure) {
  38897. onFailure();
  38898. }
  38899. return;
  38900. }
  38901. // If all optimizations were done, move to next level
  38902. if (allDone) {
  38903. currentPriorityLevel++;
  38904. }
  38905. // Let's the system running for a specific amount of time before checking FPS
  38906. scene.executeWhenReady(function () {
  38907. setTimeout(function () {
  38908. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  38909. }, options.trackerDuration);
  38910. });
  38911. };
  38912. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  38913. if (!options) {
  38914. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  38915. }
  38916. // Let's the system running for a specific amount of time before checking FPS
  38917. scene.executeWhenReady(function () {
  38918. setTimeout(function () {
  38919. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  38920. }, options.trackerDuration);
  38921. });
  38922. };
  38923. return SceneOptimizer;
  38924. })();
  38925. BABYLON.SceneOptimizer = SceneOptimizer;
  38926. })(BABYLON || (BABYLON = {}));
  38927. var BABYLON;
  38928. (function (BABYLON) {
  38929. var Internals;
  38930. (function (Internals) {
  38931. var MeshLODLevel = (function () {
  38932. function MeshLODLevel(distance, mesh) {
  38933. this.distance = distance;
  38934. this.mesh = mesh;
  38935. }
  38936. return MeshLODLevel;
  38937. })();
  38938. Internals.MeshLODLevel = MeshLODLevel;
  38939. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  38940. })(BABYLON || (BABYLON = {}));
  38941. var BABYLON;
  38942. (function (BABYLON) {
  38943. var RawTexture = (function (_super) {
  38944. __extends(RawTexture, _super);
  38945. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  38946. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38947. if (invertY === void 0) { invertY = false; }
  38948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38949. _super.call(this, null, scene, !generateMipMaps, invertY);
  38950. this.format = format;
  38951. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  38952. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38953. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38954. }
  38955. RawTexture.prototype.update = function (data) {
  38956. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  38957. };
  38958. // Statics
  38959. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38960. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38961. if (invertY === void 0) { invertY = false; }
  38962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38963. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  38964. };
  38965. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38966. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38967. if (invertY === void 0) { invertY = false; }
  38968. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38969. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38970. };
  38971. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38972. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38973. if (invertY === void 0) { invertY = false; }
  38974. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38975. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38976. };
  38977. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38978. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38979. if (invertY === void 0) { invertY = false; }
  38980. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38981. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  38982. };
  38983. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38984. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38985. if (invertY === void 0) { invertY = false; }
  38986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38987. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  38988. };
  38989. return RawTexture;
  38990. })(BABYLON.Texture);
  38991. BABYLON.RawTexture = RawTexture;
  38992. })(BABYLON || (BABYLON = {}));
  38993. var BABYLON;
  38994. (function (BABYLON) {
  38995. var IndexedVector2 = (function (_super) {
  38996. __extends(IndexedVector2, _super);
  38997. function IndexedVector2(original, index) {
  38998. _super.call(this, original.x, original.y);
  38999. this.index = index;
  39000. }
  39001. return IndexedVector2;
  39002. })(BABYLON.Vector2);
  39003. var PolygonPoints = (function () {
  39004. function PolygonPoints() {
  39005. this.elements = new Array();
  39006. }
  39007. PolygonPoints.prototype.add = function (originalPoints) {
  39008. var _this = this;
  39009. var result = new Array();
  39010. originalPoints.forEach(function (point) {
  39011. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  39012. var newPoint = new IndexedVector2(point, _this.elements.length);
  39013. result.push(newPoint);
  39014. _this.elements.push(newPoint);
  39015. }
  39016. });
  39017. return result;
  39018. };
  39019. PolygonPoints.prototype.computeBounds = function () {
  39020. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  39021. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  39022. this.elements.forEach(function (point) {
  39023. // x
  39024. if (point.x < lmin.x) {
  39025. lmin.x = point.x;
  39026. }
  39027. else if (point.x > lmax.x) {
  39028. lmax.x = point.x;
  39029. }
  39030. // y
  39031. if (point.y < lmin.y) {
  39032. lmin.y = point.y;
  39033. }
  39034. else if (point.y > lmax.y) {
  39035. lmax.y = point.y;
  39036. }
  39037. });
  39038. return {
  39039. min: lmin,
  39040. max: lmax,
  39041. width: lmax.x - lmin.x,
  39042. height: lmax.y - lmin.y
  39043. };
  39044. };
  39045. return PolygonPoints;
  39046. })();
  39047. var Polygon = (function () {
  39048. function Polygon() {
  39049. }
  39050. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  39051. return [
  39052. new BABYLON.Vector2(xmin, ymin),
  39053. new BABYLON.Vector2(xmax, ymin),
  39054. new BABYLON.Vector2(xmax, ymax),
  39055. new BABYLON.Vector2(xmin, ymax)
  39056. ];
  39057. };
  39058. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  39059. if (cx === void 0) { cx = 0; }
  39060. if (cy === void 0) { cy = 0; }
  39061. if (numberOfSides === void 0) { numberOfSides = 32; }
  39062. var result = new Array();
  39063. var angle = 0;
  39064. var increment = (Math.PI * 2) / numberOfSides;
  39065. for (var i = 0; i < numberOfSides; i++) {
  39066. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  39067. angle -= increment;
  39068. }
  39069. return result;
  39070. };
  39071. Polygon.Parse = function (input) {
  39072. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  39073. var i, result = [];
  39074. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  39075. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  39076. }
  39077. return result;
  39078. };
  39079. Polygon.StartingAt = function (x, y) {
  39080. return BABYLON.Path2.StartingAt(x, y);
  39081. };
  39082. return Polygon;
  39083. })();
  39084. BABYLON.Polygon = Polygon;
  39085. var PolygonMeshBuilder = (function () {
  39086. function PolygonMeshBuilder(name, contours, scene) {
  39087. this._points = new PolygonPoints();
  39088. this._outlinepoints = new PolygonPoints();
  39089. this._holes = [];
  39090. if (!("poly2tri" in window)) {
  39091. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  39092. }
  39093. this._name = name;
  39094. this._scene = scene;
  39095. var points;
  39096. if (contours instanceof BABYLON.Path2) {
  39097. points = contours.getPoints();
  39098. }
  39099. else {
  39100. points = contours;
  39101. }
  39102. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  39103. this._outlinepoints.add(points);
  39104. }
  39105. PolygonMeshBuilder.prototype.addHole = function (hole) {
  39106. this._swctx.addHole(this._points.add(hole));
  39107. var holepoints = new PolygonPoints();
  39108. holepoints.add(hole);
  39109. this._holes.push(holepoints);
  39110. return this;
  39111. };
  39112. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  39113. var _this = this;
  39114. if (updatable === void 0) { updatable = false; }
  39115. var result = new BABYLON.Mesh(this._name, this._scene);
  39116. var normals = [];
  39117. var positions = [];
  39118. var uvs = [];
  39119. var bounds = this._points.computeBounds();
  39120. this._points.elements.forEach(function (p) {
  39121. normals.push(0, 1.0, 0);
  39122. positions.push(p.x, 0, p.y);
  39123. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  39124. });
  39125. var indices = [];
  39126. this._swctx.triangulate();
  39127. this._swctx.getTriangles().forEach(function (triangle) {
  39128. triangle.getPoints().forEach(function (point) {
  39129. indices.push(point.index);
  39130. });
  39131. });
  39132. if (depth > 0) {
  39133. var positionscount = (positions.length / 3); //get the current pointcount
  39134. this._points.elements.forEach(function (p) {
  39135. normals.push(0, -1.0, 0);
  39136. positions.push(p.x, -depth, p.y);
  39137. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  39138. });
  39139. var p1; //we need to change order of point so the triangles are made in the rigth way.
  39140. var p2;
  39141. var poscounter = 0;
  39142. this._swctx.getTriangles().forEach(function (triangle) {
  39143. triangle.getPoints().forEach(function (point) {
  39144. switch (poscounter) {
  39145. case 0:
  39146. p1 = point;
  39147. break;
  39148. case 1:
  39149. p2 = point;
  39150. break;
  39151. case 2:
  39152. indices.push(point.index + positionscount);
  39153. indices.push(p2.index + positionscount);
  39154. indices.push(p1.index + positionscount);
  39155. poscounter = -1;
  39156. break;
  39157. }
  39158. poscounter++;
  39159. //indices.push((<IndexedVector2>point).index + positionscount);
  39160. });
  39161. });
  39162. //Add the sides
  39163. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  39164. this._holes.forEach(function (hole) {
  39165. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  39166. });
  39167. }
  39168. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  39169. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  39170. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  39171. result.setIndices(indices);
  39172. return result;
  39173. };
  39174. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  39175. var StartIndex = positions.length / 3;
  39176. var ulength = 0;
  39177. for (var i = 0; i < points.elements.length; i++) {
  39178. var p = points.elements[i];
  39179. var p1;
  39180. if ((i + 1) > points.elements.length - 1) {
  39181. p1 = points.elements[0];
  39182. }
  39183. else {
  39184. p1 = points.elements[i + 1];
  39185. }
  39186. positions.push(p.x, 0, p.y);
  39187. positions.push(p.x, -depth, p.y);
  39188. positions.push(p1.x, 0, p1.y);
  39189. positions.push(p1.x, -depth, p1.y);
  39190. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  39191. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  39192. var v3 = v2.subtract(v1);
  39193. var v4 = new BABYLON.Vector3(0, 1, 0);
  39194. var vn = BABYLON.Vector3.Cross(v3, v4);
  39195. vn = vn.normalize();
  39196. uvs.push(ulength / bounds.width, 0);
  39197. uvs.push(ulength / bounds.width, 1);
  39198. ulength += v3.length();
  39199. uvs.push((ulength / bounds.width), 0);
  39200. uvs.push((ulength / bounds.width), 1);
  39201. if (!flip) {
  39202. normals.push(-vn.x, -vn.y, -vn.z);
  39203. normals.push(-vn.x, -vn.y, -vn.z);
  39204. normals.push(-vn.x, -vn.y, -vn.z);
  39205. normals.push(-vn.x, -vn.y, -vn.z);
  39206. indices.push(StartIndex);
  39207. indices.push(StartIndex + 1);
  39208. indices.push(StartIndex + 2);
  39209. indices.push(StartIndex + 1);
  39210. indices.push(StartIndex + 3);
  39211. indices.push(StartIndex + 2);
  39212. }
  39213. else {
  39214. normals.push(vn.x, vn.y, vn.z);
  39215. normals.push(vn.x, vn.y, vn.z);
  39216. normals.push(vn.x, vn.y, vn.z);
  39217. normals.push(vn.x, vn.y, vn.z);
  39218. indices.push(StartIndex);
  39219. indices.push(StartIndex + 2);
  39220. indices.push(StartIndex + 1);
  39221. indices.push(StartIndex + 1);
  39222. indices.push(StartIndex + 2);
  39223. indices.push(StartIndex + 3);
  39224. }
  39225. StartIndex += 4;
  39226. }
  39227. ;
  39228. };
  39229. return PolygonMeshBuilder;
  39230. })();
  39231. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  39232. })(BABYLON || (BABYLON = {}));
  39233. var BABYLON;
  39234. (function (BABYLON) {
  39235. var Octree = (function () {
  39236. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  39237. if (maxDepth === void 0) { maxDepth = 2; }
  39238. this.maxDepth = maxDepth;
  39239. this.dynamicContent = new Array();
  39240. this._maxBlockCapacity = maxBlockCapacity || 64;
  39241. this._selectionContent = new BABYLON.SmartArray(1024);
  39242. this._creationFunc = creationFunc;
  39243. }
  39244. // Methods
  39245. Octree.prototype.update = function (worldMin, worldMax, entries) {
  39246. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  39247. };
  39248. Octree.prototype.addMesh = function (entry) {
  39249. for (var index = 0; index < this.blocks.length; index++) {
  39250. var block = this.blocks[index];
  39251. block.addEntry(entry);
  39252. }
  39253. };
  39254. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  39255. this._selectionContent.reset();
  39256. for (var index = 0; index < this.blocks.length; index++) {
  39257. var block = this.blocks[index];
  39258. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  39259. }
  39260. if (allowDuplicate) {
  39261. this._selectionContent.concat(this.dynamicContent);
  39262. }
  39263. else {
  39264. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  39265. }
  39266. return this._selectionContent;
  39267. };
  39268. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  39269. this._selectionContent.reset();
  39270. for (var index = 0; index < this.blocks.length; index++) {
  39271. var block = this.blocks[index];
  39272. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  39273. }
  39274. if (allowDuplicate) {
  39275. this._selectionContent.concat(this.dynamicContent);
  39276. }
  39277. else {
  39278. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  39279. }
  39280. return this._selectionContent;
  39281. };
  39282. Octree.prototype.intersectsRay = function (ray) {
  39283. this._selectionContent.reset();
  39284. for (var index = 0; index < this.blocks.length; index++) {
  39285. var block = this.blocks[index];
  39286. block.intersectsRay(ray, this._selectionContent);
  39287. }
  39288. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  39289. return this._selectionContent;
  39290. };
  39291. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  39292. target.blocks = new Array();
  39293. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  39294. // Segmenting space
  39295. for (var x = 0; x < 2; x++) {
  39296. for (var y = 0; y < 2; y++) {
  39297. for (var z = 0; z < 2; z++) {
  39298. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  39299. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  39300. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  39301. block.addEntries(entries);
  39302. target.blocks.push(block);
  39303. }
  39304. }
  39305. }
  39306. };
  39307. Octree.CreationFuncForMeshes = function (entry, block) {
  39308. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  39309. block.entries.push(entry);
  39310. }
  39311. };
  39312. Octree.CreationFuncForSubMeshes = function (entry, block) {
  39313. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  39314. block.entries.push(entry);
  39315. }
  39316. };
  39317. return Octree;
  39318. })();
  39319. BABYLON.Octree = Octree;
  39320. })(BABYLON || (BABYLON = {}));
  39321. var BABYLON;
  39322. (function (BABYLON) {
  39323. var OctreeBlock = (function () {
  39324. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  39325. this.entries = new Array();
  39326. this._boundingVectors = new Array();
  39327. this._capacity = capacity;
  39328. this._depth = depth;
  39329. this._maxDepth = maxDepth;
  39330. this._creationFunc = creationFunc;
  39331. this._minPoint = minPoint;
  39332. this._maxPoint = maxPoint;
  39333. this._boundingVectors.push(minPoint.clone());
  39334. this._boundingVectors.push(maxPoint.clone());
  39335. this._boundingVectors.push(minPoint.clone());
  39336. this._boundingVectors[2].x = maxPoint.x;
  39337. this._boundingVectors.push(minPoint.clone());
  39338. this._boundingVectors[3].y = maxPoint.y;
  39339. this._boundingVectors.push(minPoint.clone());
  39340. this._boundingVectors[4].z = maxPoint.z;
  39341. this._boundingVectors.push(maxPoint.clone());
  39342. this._boundingVectors[5].z = minPoint.z;
  39343. this._boundingVectors.push(maxPoint.clone());
  39344. this._boundingVectors[6].x = minPoint.x;
  39345. this._boundingVectors.push(maxPoint.clone());
  39346. this._boundingVectors[7].y = minPoint.y;
  39347. }
  39348. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  39349. // Property
  39350. get: function () {
  39351. return this._capacity;
  39352. },
  39353. enumerable: true,
  39354. configurable: true
  39355. });
  39356. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  39357. get: function () {
  39358. return this._minPoint;
  39359. },
  39360. enumerable: true,
  39361. configurable: true
  39362. });
  39363. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  39364. get: function () {
  39365. return this._maxPoint;
  39366. },
  39367. enumerable: true,
  39368. configurable: true
  39369. });
  39370. // Methods
  39371. OctreeBlock.prototype.addEntry = function (entry) {
  39372. if (this.blocks) {
  39373. for (var index = 0; index < this.blocks.length; index++) {
  39374. var block = this.blocks[index];
  39375. block.addEntry(entry);
  39376. }
  39377. return;
  39378. }
  39379. this._creationFunc(entry, this);
  39380. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  39381. this.createInnerBlocks();
  39382. }
  39383. };
  39384. OctreeBlock.prototype.addEntries = function (entries) {
  39385. for (var index = 0; index < entries.length; index++) {
  39386. var mesh = entries[index];
  39387. this.addEntry(mesh);
  39388. }
  39389. };
  39390. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  39391. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  39392. if (this.blocks) {
  39393. for (var index = 0; index < this.blocks.length; index++) {
  39394. var block = this.blocks[index];
  39395. block.select(frustumPlanes, selection, allowDuplicate);
  39396. }
  39397. return;
  39398. }
  39399. if (allowDuplicate) {
  39400. selection.concat(this.entries);
  39401. }
  39402. else {
  39403. selection.concatWithNoDuplicate(this.entries);
  39404. }
  39405. }
  39406. };
  39407. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  39408. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  39409. if (this.blocks) {
  39410. for (var index = 0; index < this.blocks.length; index++) {
  39411. var block = this.blocks[index];
  39412. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  39413. }
  39414. return;
  39415. }
  39416. if (allowDuplicate) {
  39417. selection.concat(this.entries);
  39418. }
  39419. else {
  39420. selection.concatWithNoDuplicate(this.entries);
  39421. }
  39422. }
  39423. };
  39424. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  39425. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  39426. if (this.blocks) {
  39427. for (var index = 0; index < this.blocks.length; index++) {
  39428. var block = this.blocks[index];
  39429. block.intersectsRay(ray, selection);
  39430. }
  39431. return;
  39432. }
  39433. selection.concatWithNoDuplicate(this.entries);
  39434. }
  39435. };
  39436. OctreeBlock.prototype.createInnerBlocks = function () {
  39437. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  39438. };
  39439. return OctreeBlock;
  39440. })();
  39441. BABYLON.OctreeBlock = OctreeBlock;
  39442. })(BABYLON || (BABYLON = {}));
  39443. var BABYLON;
  39444. (function (BABYLON) {
  39445. var BlurPostProcess = (function (_super) {
  39446. __extends(BlurPostProcess, _super);
  39447. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  39448. var _this = this;
  39449. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39450. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  39451. this.direction = direction;
  39452. this.blurWidth = blurWidth;
  39453. this.onApply = function (effect) {
  39454. effect.setFloat2("screenSize", _this.width, _this.height);
  39455. effect.setVector2("direction", _this.direction);
  39456. effect.setFloat("blurWidth", _this.blurWidth);
  39457. };
  39458. }
  39459. return BlurPostProcess;
  39460. })(BABYLON.PostProcess);
  39461. BABYLON.BlurPostProcess = BlurPostProcess;
  39462. })(BABYLON || (BABYLON = {}));
  39463. var BABYLON;
  39464. (function (BABYLON) {
  39465. var RefractionPostProcess = (function (_super) {
  39466. __extends(RefractionPostProcess, _super);
  39467. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  39468. var _this = this;
  39469. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  39470. this.color = color;
  39471. this.depth = depth;
  39472. this.colorLevel = colorLevel;
  39473. this.onActivate = function (cam) {
  39474. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  39475. };
  39476. this.onApply = function (effect) {
  39477. effect.setColor3("baseColor", _this.color);
  39478. effect.setFloat("depth", _this.depth);
  39479. effect.setFloat("colorLevel", _this.colorLevel);
  39480. effect.setTexture("refractionSampler", _this._refRexture);
  39481. };
  39482. }
  39483. // Methods
  39484. RefractionPostProcess.prototype.dispose = function (camera) {
  39485. if (this._refRexture) {
  39486. this._refRexture.dispose();
  39487. }
  39488. _super.prototype.dispose.call(this, camera);
  39489. };
  39490. return RefractionPostProcess;
  39491. })(BABYLON.PostProcess);
  39492. BABYLON.RefractionPostProcess = RefractionPostProcess;
  39493. })(BABYLON || (BABYLON = {}));
  39494. var BABYLON;
  39495. (function (BABYLON) {
  39496. var BlackAndWhitePostProcess = (function (_super) {
  39497. __extends(BlackAndWhitePostProcess, _super);
  39498. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  39499. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  39500. }
  39501. return BlackAndWhitePostProcess;
  39502. })(BABYLON.PostProcess);
  39503. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  39504. })(BABYLON || (BABYLON = {}));
  39505. var BABYLON;
  39506. (function (BABYLON) {
  39507. var ConvolutionPostProcess = (function (_super) {
  39508. __extends(ConvolutionPostProcess, _super);
  39509. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  39510. var _this = this;
  39511. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  39512. this.kernel = kernel;
  39513. this.onApply = function (effect) {
  39514. effect.setFloat2("screenSize", _this.width, _this.height);
  39515. effect.setArray("kernel", _this.kernel);
  39516. };
  39517. }
  39518. // Statics
  39519. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  39520. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  39521. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  39522. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  39523. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  39524. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  39525. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  39526. return ConvolutionPostProcess;
  39527. })(BABYLON.PostProcess);
  39528. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  39529. })(BABYLON || (BABYLON = {}));
  39530. var BABYLON;
  39531. (function (BABYLON) {
  39532. var FilterPostProcess = (function (_super) {
  39533. __extends(FilterPostProcess, _super);
  39534. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  39535. var _this = this;
  39536. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  39537. this.kernelMatrix = kernelMatrix;
  39538. this.onApply = function (effect) {
  39539. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  39540. };
  39541. }
  39542. return FilterPostProcess;
  39543. })(BABYLON.PostProcess);
  39544. BABYLON.FilterPostProcess = FilterPostProcess;
  39545. })(BABYLON || (BABYLON = {}));
  39546. var BABYLON;
  39547. (function (BABYLON) {
  39548. var FxaaPostProcess = (function (_super) {
  39549. __extends(FxaaPostProcess, _super);
  39550. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  39551. var _this = this;
  39552. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  39553. this.onSizeChanged = function () {
  39554. _this.texelWidth = 1.0 / _this.width;
  39555. _this.texelHeight = 1.0 / _this.height;
  39556. };
  39557. this.onApply = function (effect) {
  39558. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  39559. };
  39560. }
  39561. return FxaaPostProcess;
  39562. })(BABYLON.PostProcess);
  39563. BABYLON.FxaaPostProcess = FxaaPostProcess;
  39564. })(BABYLON || (BABYLON = {}));
  39565. var BABYLON;
  39566. (function (BABYLON) {
  39567. var StereoscopicInterlacePostProcess = (function (_super) {
  39568. __extends(StereoscopicInterlacePostProcess, _super);
  39569. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  39570. var _this = this;
  39571. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  39572. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  39573. this.onSizeChanged = function () {
  39574. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  39575. };
  39576. this.onApply = function (effect) {
  39577. effect.setTextureFromPostProcess("camASampler", postProcessA);
  39578. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  39579. };
  39580. }
  39581. return StereoscopicInterlacePostProcess;
  39582. })(BABYLON.PostProcess);
  39583. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  39584. })(BABYLON || (BABYLON = {}));
  39585. var BABYLON;
  39586. (function (BABYLON) {
  39587. var LensFlare = (function () {
  39588. function LensFlare(size, position, color, imgUrl, system) {
  39589. this.size = size;
  39590. this.position = position;
  39591. this.dispose = function () {
  39592. if (this.texture) {
  39593. this.texture.dispose();
  39594. }
  39595. // Remove from scene
  39596. var index = this._system.lensFlares.indexOf(this);
  39597. this._system.lensFlares.splice(index, 1);
  39598. };
  39599. this.color = color || new BABYLON.Color3(1, 1, 1);
  39600. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  39601. this._system = system;
  39602. system.lensFlares.push(this);
  39603. }
  39604. return LensFlare;
  39605. })();
  39606. BABYLON.LensFlare = LensFlare;
  39607. })(BABYLON || (BABYLON = {}));
  39608. var BABYLON;
  39609. (function (BABYLON) {
  39610. var LensFlareSystem = (function () {
  39611. function LensFlareSystem(name, emitter, scene) {
  39612. this.name = name;
  39613. this.lensFlares = new Array();
  39614. this.borderLimit = 300;
  39615. this.layerMask = 0x0FFFFFFF;
  39616. this._vertexDeclaration = [2];
  39617. this._vertexStrideSize = 2 * 4;
  39618. this._isEnabled = true;
  39619. this._scene = scene;
  39620. this._emitter = emitter;
  39621. this.id = name;
  39622. scene.lensFlareSystems.push(this);
  39623. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  39624. // VBO
  39625. var vertices = [];
  39626. vertices.push(1, 1);
  39627. vertices.push(-1, 1);
  39628. vertices.push(-1, -1);
  39629. vertices.push(1, -1);
  39630. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  39631. // Indices
  39632. var indices = [];
  39633. indices.push(0);
  39634. indices.push(1);
  39635. indices.push(2);
  39636. indices.push(0);
  39637. indices.push(2);
  39638. indices.push(3);
  39639. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  39640. // Effects
  39641. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  39642. }
  39643. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  39644. get: function () {
  39645. return this._isEnabled;
  39646. },
  39647. set: function (value) {
  39648. this._isEnabled = value;
  39649. },
  39650. enumerable: true,
  39651. configurable: true
  39652. });
  39653. LensFlareSystem.prototype.getScene = function () {
  39654. return this._scene;
  39655. };
  39656. LensFlareSystem.prototype.getEmitter = function () {
  39657. return this._emitter;
  39658. };
  39659. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  39660. this._emitter = newEmitter;
  39661. };
  39662. LensFlareSystem.prototype.getEmitterPosition = function () {
  39663. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  39664. };
  39665. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  39666. var position = this.getEmitterPosition();
  39667. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  39668. this._positionX = position.x;
  39669. this._positionY = position.y;
  39670. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  39671. if (position.z > 0) {
  39672. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  39673. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  39674. return true;
  39675. }
  39676. }
  39677. return false;
  39678. };
  39679. LensFlareSystem.prototype._isVisible = function () {
  39680. if (!this._isEnabled) {
  39681. return false;
  39682. }
  39683. var emitterPosition = this.getEmitterPosition();
  39684. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  39685. var distance = direction.length();
  39686. direction.normalize();
  39687. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  39688. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  39689. return !pickInfo.hit || pickInfo.distance > distance;
  39690. };
  39691. LensFlareSystem.prototype.render = function () {
  39692. if (!this._effect.isReady())
  39693. return false;
  39694. var engine = this._scene.getEngine();
  39695. var viewport = this._scene.activeCamera.viewport;
  39696. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  39697. // Position
  39698. if (!this.computeEffectivePosition(globalViewport)) {
  39699. return false;
  39700. }
  39701. // Visibility
  39702. if (!this._isVisible()) {
  39703. return false;
  39704. }
  39705. // Intensity
  39706. var awayX;
  39707. var awayY;
  39708. if (this._positionX < this.borderLimit + globalViewport.x) {
  39709. awayX = this.borderLimit + globalViewport.x - this._positionX;
  39710. }
  39711. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  39712. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  39713. }
  39714. else {
  39715. awayX = 0;
  39716. }
  39717. if (this._positionY < this.borderLimit + globalViewport.y) {
  39718. awayY = this.borderLimit + globalViewport.y - this._positionY;
  39719. }
  39720. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  39721. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  39722. }
  39723. else {
  39724. awayY = 0;
  39725. }
  39726. var away = (awayX > awayY) ? awayX : awayY;
  39727. if (away > this.borderLimit) {
  39728. away = this.borderLimit;
  39729. }
  39730. var intensity = 1.0 - (away / this.borderLimit);
  39731. if (intensity < 0) {
  39732. return false;
  39733. }
  39734. if (intensity > 1.0) {
  39735. intensity = 1.0;
  39736. }
  39737. // Position
  39738. var centerX = globalViewport.x + globalViewport.width / 2;
  39739. var centerY = globalViewport.y + globalViewport.height / 2;
  39740. var distX = centerX - this._positionX;
  39741. var distY = centerY - this._positionY;
  39742. // Effects
  39743. engine.enableEffect(this._effect);
  39744. engine.setState(false);
  39745. engine.setDepthBuffer(false);
  39746. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  39747. // VBOs
  39748. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  39749. // Flares
  39750. for (var index = 0; index < this.lensFlares.length; index++) {
  39751. var flare = this.lensFlares[index];
  39752. var x = centerX - (distX * flare.position);
  39753. var y = centerY - (distY * flare.position);
  39754. var cw = flare.size;
  39755. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  39756. var cx = 2 * (x / globalViewport.width) - 1.0;
  39757. var cy = 1.0 - 2 * (y / globalViewport.height);
  39758. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  39759. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  39760. // Texture
  39761. this._effect.setTexture("textureSampler", flare.texture);
  39762. // Color
  39763. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  39764. // Draw order
  39765. engine.draw(true, 0, 6);
  39766. }
  39767. engine.setDepthBuffer(true);
  39768. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39769. return true;
  39770. };
  39771. LensFlareSystem.prototype.dispose = function () {
  39772. if (this._vertexBuffer) {
  39773. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  39774. this._vertexBuffer = null;
  39775. }
  39776. if (this._indexBuffer) {
  39777. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39778. this._indexBuffer = null;
  39779. }
  39780. while (this.lensFlares.length) {
  39781. this.lensFlares[0].dispose();
  39782. }
  39783. // Remove from scene
  39784. var index = this._scene.lensFlareSystems.indexOf(this);
  39785. this._scene.lensFlareSystems.splice(index, 1);
  39786. };
  39787. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  39788. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  39789. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  39790. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  39791. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  39792. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  39793. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  39794. var parsedFlare = parsedLensFlareSystem.flares[index];
  39795. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  39796. }
  39797. return lensFlareSystem;
  39798. };
  39799. LensFlareSystem.prototype.serialize = function () {
  39800. var serializationObject = {};
  39801. serializationObject.id = this.id;
  39802. serializationObject.name = this.name;
  39803. serializationObject.emitterId = this.getEmitter().id;
  39804. serializationObject.borderLimit = this.borderLimit;
  39805. serializationObject.flares = [];
  39806. for (var index = 0; index < this.lensFlares.length; index++) {
  39807. var flare = this.lensFlares[index];
  39808. serializationObject.flares.push({
  39809. size: flare.size,
  39810. position: flare.position,
  39811. color: flare.color.asArray(),
  39812. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  39813. });
  39814. }
  39815. return serializationObject;
  39816. };
  39817. return LensFlareSystem;
  39818. })();
  39819. BABYLON.LensFlareSystem = LensFlareSystem;
  39820. })(BABYLON || (BABYLON = {}));
  39821. var BABYLON;
  39822. (function (BABYLON) {
  39823. // We're mainly based on the logic defined into the FreeCamera code
  39824. var DeviceOrientationCamera = (function (_super) {
  39825. __extends(DeviceOrientationCamera, _super);
  39826. //-- end properties for backward compatibility for inputs
  39827. function DeviceOrientationCamera(name, position, scene) {
  39828. _super.call(this, name, position, scene);
  39829. this.inputs.addDeviceOrientation();
  39830. }
  39831. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  39832. //-- Begin properties for backward compatibility for inputs
  39833. get: function () {
  39834. var gamepad = this.inputs.attached["deviceOrientation"];
  39835. if (gamepad)
  39836. return gamepad.angularSensibility;
  39837. },
  39838. set: function (value) {
  39839. var gamepad = this.inputs.attached["deviceOrientation"];
  39840. if (gamepad)
  39841. gamepad.angularSensibility = value;
  39842. },
  39843. enumerable: true,
  39844. configurable: true
  39845. });
  39846. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  39847. get: function () {
  39848. var gamepad = this.inputs.attached["deviceOrientation"];
  39849. if (gamepad)
  39850. return gamepad.moveSensibility;
  39851. },
  39852. set: function (value) {
  39853. var gamepad = this.inputs.attached["deviceOrientation"];
  39854. if (gamepad)
  39855. gamepad.moveSensibility = value;
  39856. },
  39857. enumerable: true,
  39858. configurable: true
  39859. });
  39860. DeviceOrientationCamera.prototype.getTypeName = function () {
  39861. return "DeviceOrientationCamera";
  39862. };
  39863. return DeviceOrientationCamera;
  39864. })(BABYLON.FreeCamera);
  39865. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  39866. })(BABYLON || (BABYLON = {}));
  39867. var BABYLON;
  39868. (function (BABYLON) {
  39869. // We're mainly based on the logic defined into the FreeCamera code
  39870. var UniversalCamera = (function (_super) {
  39871. __extends(UniversalCamera, _super);
  39872. //-- end properties for backward compatibility for inputs
  39873. function UniversalCamera(name, position, scene) {
  39874. _super.call(this, name, position, scene);
  39875. this.inputs.addGamepad();
  39876. }
  39877. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  39878. //-- Begin properties for backward compatibility for inputs
  39879. get: function () {
  39880. var gamepad = this.inputs.attached["gamepad"];
  39881. if (gamepad)
  39882. return gamepad.gamepadAngularSensibility;
  39883. },
  39884. set: function (value) {
  39885. var gamepad = this.inputs.attached["gamepad"];
  39886. if (gamepad)
  39887. gamepad.gamepadAngularSensibility = value;
  39888. },
  39889. enumerable: true,
  39890. configurable: true
  39891. });
  39892. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  39893. get: function () {
  39894. var gamepad = this.inputs.attached["gamepad"];
  39895. if (gamepad)
  39896. return gamepad.gamepadMoveSensibility;
  39897. },
  39898. set: function (value) {
  39899. var gamepad = this.inputs.attached["gamepad"];
  39900. if (gamepad)
  39901. gamepad.gamepadMoveSensibility = value;
  39902. },
  39903. enumerable: true,
  39904. configurable: true
  39905. });
  39906. UniversalCamera.prototype.getTypeName = function () {
  39907. return "UniversalCamera";
  39908. };
  39909. return UniversalCamera;
  39910. })(BABYLON.TouchCamera);
  39911. BABYLON.UniversalCamera = UniversalCamera;
  39912. })(BABYLON || (BABYLON = {}));
  39913. var BABYLON;
  39914. (function (BABYLON) {
  39915. var Gamepads = (function () {
  39916. function Gamepads(ongamedpadconnected) {
  39917. var _this = this;
  39918. this.babylonGamepads = [];
  39919. this.oneGamepadConnected = false;
  39920. this.isMonitoring = false;
  39921. this.gamepadEventSupported = 'GamepadEvent' in window;
  39922. this.gamepadSupportAvailable = (navigator.getGamepads ||
  39923. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  39924. this._callbackGamepadConnected = ongamedpadconnected;
  39925. if (this.gamepadSupportAvailable) {
  39926. // Checking if the gamepad connected event is supported (like in Firefox)
  39927. if (this.gamepadEventSupported) {
  39928. this._onGamepadConnectedEvent = function (evt) {
  39929. _this._onGamepadConnected(evt);
  39930. };
  39931. this._onGamepadDisonnectedEvent = function (evt) {
  39932. _this._onGamepadDisconnected(evt);
  39933. };
  39934. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  39935. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  39936. }
  39937. else {
  39938. this._startMonitoringGamepads();
  39939. }
  39940. }
  39941. }
  39942. Gamepads.prototype.dispose = function () {
  39943. if (Gamepads.gamepadDOMInfo) {
  39944. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39945. }
  39946. if (this._onGamepadConnectedEvent) {
  39947. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  39948. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  39949. this._onGamepadConnectedEvent = null;
  39950. this._onGamepadDisonnectedEvent = null;
  39951. }
  39952. };
  39953. Gamepads.prototype._onGamepadConnected = function (evt) {
  39954. var newGamepad = this._addNewGamepad(evt.gamepad);
  39955. if (this._callbackGamepadConnected)
  39956. this._callbackGamepadConnected(newGamepad);
  39957. this._startMonitoringGamepads();
  39958. };
  39959. Gamepads.prototype._addNewGamepad = function (gamepad) {
  39960. if (!this.oneGamepadConnected) {
  39961. this.oneGamepadConnected = true;
  39962. if (Gamepads.gamepadDOMInfo) {
  39963. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39964. Gamepads.gamepadDOMInfo = null;
  39965. }
  39966. }
  39967. var newGamepad;
  39968. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  39969. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  39970. }
  39971. else {
  39972. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  39973. }
  39974. this.babylonGamepads.push(newGamepad);
  39975. return newGamepad;
  39976. };
  39977. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  39978. // Remove the gamepad from the list of gamepads to monitor.
  39979. for (var i in this.babylonGamepads) {
  39980. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  39981. this.babylonGamepads.splice(+i, 1);
  39982. break;
  39983. }
  39984. }
  39985. // If no gamepads are left, stop the polling loop.
  39986. if (this.babylonGamepads.length == 0) {
  39987. this._stopMonitoringGamepads();
  39988. }
  39989. };
  39990. Gamepads.prototype._startMonitoringGamepads = function () {
  39991. if (!this.isMonitoring) {
  39992. this.isMonitoring = true;
  39993. this._checkGamepadsStatus();
  39994. }
  39995. };
  39996. Gamepads.prototype._stopMonitoringGamepads = function () {
  39997. this.isMonitoring = false;
  39998. };
  39999. Gamepads.prototype._checkGamepadsStatus = function () {
  40000. var _this = this;
  40001. // updating gamepad objects
  40002. this._updateGamepadObjects();
  40003. for (var i in this.babylonGamepads) {
  40004. this.babylonGamepads[i].update();
  40005. }
  40006. if (this.isMonitoring) {
  40007. if (window.requestAnimationFrame) {
  40008. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  40009. }
  40010. else if (window.mozRequestAnimationFrame) {
  40011. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  40012. }
  40013. else if (window.webkitRequestAnimationFrame) {
  40014. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  40015. }
  40016. }
  40017. };
  40018. // This function is called only on Chrome, which does not yet support
  40019. // connection/disconnection events, but requires you to monitor
  40020. // an array for changes.
  40021. Gamepads.prototype._updateGamepadObjects = function () {
  40022. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  40023. for (var i = 0; i < gamepads.length; i++) {
  40024. if (gamepads[i]) {
  40025. if (!(gamepads[i].index in this.babylonGamepads)) {
  40026. var newGamepad = this._addNewGamepad(gamepads[i]);
  40027. if (this._callbackGamepadConnected) {
  40028. this._callbackGamepadConnected(newGamepad);
  40029. }
  40030. }
  40031. else {
  40032. this.babylonGamepads[i].browserGamepad = gamepads[i];
  40033. }
  40034. }
  40035. }
  40036. };
  40037. return Gamepads;
  40038. })();
  40039. BABYLON.Gamepads = Gamepads;
  40040. var StickValues = (function () {
  40041. function StickValues(x, y) {
  40042. this.x = x;
  40043. this.y = y;
  40044. }
  40045. return StickValues;
  40046. })();
  40047. BABYLON.StickValues = StickValues;
  40048. var Gamepad = (function () {
  40049. function Gamepad(id, index, browserGamepad) {
  40050. this.id = id;
  40051. this.index = index;
  40052. this.browserGamepad = browserGamepad;
  40053. if (this.browserGamepad.axes.length >= 2) {
  40054. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  40055. }
  40056. if (this.browserGamepad.axes.length >= 4) {
  40057. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  40058. }
  40059. }
  40060. Gamepad.prototype.onleftstickchanged = function (callback) {
  40061. this._onleftstickchanged = callback;
  40062. };
  40063. Gamepad.prototype.onrightstickchanged = function (callback) {
  40064. this._onrightstickchanged = callback;
  40065. };
  40066. Object.defineProperty(Gamepad.prototype, "leftStick", {
  40067. get: function () {
  40068. return this._leftStick;
  40069. },
  40070. set: function (newValues) {
  40071. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  40072. this._onleftstickchanged(newValues);
  40073. }
  40074. this._leftStick = newValues;
  40075. },
  40076. enumerable: true,
  40077. configurable: true
  40078. });
  40079. Object.defineProperty(Gamepad.prototype, "rightStick", {
  40080. get: function () {
  40081. return this._rightStick;
  40082. },
  40083. set: function (newValues) {
  40084. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  40085. this._onrightstickchanged(newValues);
  40086. }
  40087. this._rightStick = newValues;
  40088. },
  40089. enumerable: true,
  40090. configurable: true
  40091. });
  40092. Gamepad.prototype.update = function () {
  40093. if (this._leftStick) {
  40094. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  40095. }
  40096. if (this._rightStick) {
  40097. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  40098. }
  40099. };
  40100. return Gamepad;
  40101. })();
  40102. BABYLON.Gamepad = Gamepad;
  40103. var GenericPad = (function (_super) {
  40104. __extends(GenericPad, _super);
  40105. function GenericPad(id, index, gamepad) {
  40106. _super.call(this, id, index, gamepad);
  40107. this.id = id;
  40108. this.index = index;
  40109. this.gamepad = gamepad;
  40110. this._buttons = new Array(gamepad.buttons.length);
  40111. }
  40112. GenericPad.prototype.onbuttondown = function (callback) {
  40113. this._onbuttondown = callback;
  40114. };
  40115. GenericPad.prototype.onbuttonup = function (callback) {
  40116. this._onbuttonup = callback;
  40117. };
  40118. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  40119. if (newValue !== currentValue) {
  40120. if (this._onbuttondown && newValue === 1) {
  40121. this._onbuttondown(buttonIndex);
  40122. }
  40123. if (this._onbuttonup && newValue === 0) {
  40124. this._onbuttonup(buttonIndex);
  40125. }
  40126. }
  40127. return newValue;
  40128. };
  40129. GenericPad.prototype.update = function () {
  40130. _super.prototype.update.call(this);
  40131. for (var index = 0; index < this._buttons.length; index++) {
  40132. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  40133. }
  40134. };
  40135. return GenericPad;
  40136. })(Gamepad);
  40137. BABYLON.GenericPad = GenericPad;
  40138. (function (Xbox360Button) {
  40139. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  40140. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  40141. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  40142. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  40143. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  40144. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  40145. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  40146. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  40147. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  40148. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  40149. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  40150. var Xbox360Button = BABYLON.Xbox360Button;
  40151. (function (Xbox360Dpad) {
  40152. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  40153. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  40154. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  40155. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  40156. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  40157. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  40158. var Xbox360Pad = (function (_super) {
  40159. __extends(Xbox360Pad, _super);
  40160. function Xbox360Pad() {
  40161. _super.apply(this, arguments);
  40162. this._leftTrigger = 0;
  40163. this._rightTrigger = 0;
  40164. this._buttonA = 0;
  40165. this._buttonB = 0;
  40166. this._buttonX = 0;
  40167. this._buttonY = 0;
  40168. this._buttonBack = 0;
  40169. this._buttonStart = 0;
  40170. this._buttonLB = 0;
  40171. this._buttonRB = 0;
  40172. this._buttonLeftStick = 0;
  40173. this._buttonRightStick = 0;
  40174. this._dPadUp = 0;
  40175. this._dPadDown = 0;
  40176. this._dPadLeft = 0;
  40177. this._dPadRight = 0;
  40178. }
  40179. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  40180. this._onlefttriggerchanged = callback;
  40181. };
  40182. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  40183. this._onrighttriggerchanged = callback;
  40184. };
  40185. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  40186. get: function () {
  40187. return this._leftTrigger;
  40188. },
  40189. set: function (newValue) {
  40190. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  40191. this._onlefttriggerchanged(newValue);
  40192. }
  40193. this._leftTrigger = newValue;
  40194. },
  40195. enumerable: true,
  40196. configurable: true
  40197. });
  40198. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  40199. get: function () {
  40200. return this._rightTrigger;
  40201. },
  40202. set: function (newValue) {
  40203. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  40204. this._onrighttriggerchanged(newValue);
  40205. }
  40206. this._rightTrigger = newValue;
  40207. },
  40208. enumerable: true,
  40209. configurable: true
  40210. });
  40211. Xbox360Pad.prototype.onbuttondown = function (callback) {
  40212. this._onbuttondown = callback;
  40213. };
  40214. Xbox360Pad.prototype.onbuttonup = function (callback) {
  40215. this._onbuttonup = callback;
  40216. };
  40217. Xbox360Pad.prototype.ondpaddown = function (callback) {
  40218. this._ondpaddown = callback;
  40219. };
  40220. Xbox360Pad.prototype.ondpadup = function (callback) {
  40221. this._ondpadup = callback;
  40222. };
  40223. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  40224. if (newValue !== currentValue) {
  40225. if (this._onbuttondown && newValue === 1) {
  40226. this._onbuttondown(buttonType);
  40227. }
  40228. if (this._onbuttonup && newValue === 0) {
  40229. this._onbuttonup(buttonType);
  40230. }
  40231. }
  40232. return newValue;
  40233. };
  40234. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  40235. if (newValue !== currentValue) {
  40236. if (this._ondpaddown && newValue === 1) {
  40237. this._ondpaddown(buttonType);
  40238. }
  40239. if (this._ondpadup && newValue === 0) {
  40240. this._ondpadup(buttonType);
  40241. }
  40242. }
  40243. return newValue;
  40244. };
  40245. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  40246. get: function () {
  40247. return this._buttonA;
  40248. },
  40249. set: function (value) {
  40250. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  40251. },
  40252. enumerable: true,
  40253. configurable: true
  40254. });
  40255. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  40256. get: function () {
  40257. return this._buttonB;
  40258. },
  40259. set: function (value) {
  40260. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  40261. },
  40262. enumerable: true,
  40263. configurable: true
  40264. });
  40265. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  40266. get: function () {
  40267. return this._buttonX;
  40268. },
  40269. set: function (value) {
  40270. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  40271. },
  40272. enumerable: true,
  40273. configurable: true
  40274. });
  40275. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  40276. get: function () {
  40277. return this._buttonY;
  40278. },
  40279. set: function (value) {
  40280. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  40281. },
  40282. enumerable: true,
  40283. configurable: true
  40284. });
  40285. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  40286. get: function () {
  40287. return this._buttonStart;
  40288. },
  40289. set: function (value) {
  40290. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  40291. },
  40292. enumerable: true,
  40293. configurable: true
  40294. });
  40295. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  40296. get: function () {
  40297. return this._buttonBack;
  40298. },
  40299. set: function (value) {
  40300. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  40301. },
  40302. enumerable: true,
  40303. configurable: true
  40304. });
  40305. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  40306. get: function () {
  40307. return this._buttonLB;
  40308. },
  40309. set: function (value) {
  40310. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  40311. },
  40312. enumerable: true,
  40313. configurable: true
  40314. });
  40315. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  40316. get: function () {
  40317. return this._buttonRB;
  40318. },
  40319. set: function (value) {
  40320. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  40321. },
  40322. enumerable: true,
  40323. configurable: true
  40324. });
  40325. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  40326. get: function () {
  40327. return this._buttonLeftStick;
  40328. },
  40329. set: function (value) {
  40330. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  40331. },
  40332. enumerable: true,
  40333. configurable: true
  40334. });
  40335. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  40336. get: function () {
  40337. return this._buttonRightStick;
  40338. },
  40339. set: function (value) {
  40340. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  40341. },
  40342. enumerable: true,
  40343. configurable: true
  40344. });
  40345. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  40346. get: function () {
  40347. return this._dPadUp;
  40348. },
  40349. set: function (value) {
  40350. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  40351. },
  40352. enumerable: true,
  40353. configurable: true
  40354. });
  40355. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  40356. get: function () {
  40357. return this._dPadDown;
  40358. },
  40359. set: function (value) {
  40360. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  40361. },
  40362. enumerable: true,
  40363. configurable: true
  40364. });
  40365. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  40366. get: function () {
  40367. return this._dPadLeft;
  40368. },
  40369. set: function (value) {
  40370. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  40371. },
  40372. enumerable: true,
  40373. configurable: true
  40374. });
  40375. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  40376. get: function () {
  40377. return this._dPadRight;
  40378. },
  40379. set: function (value) {
  40380. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  40381. },
  40382. enumerable: true,
  40383. configurable: true
  40384. });
  40385. Xbox360Pad.prototype.update = function () {
  40386. _super.prototype.update.call(this);
  40387. this.buttonA = this.browserGamepad.buttons[0].value;
  40388. this.buttonB = this.browserGamepad.buttons[1].value;
  40389. this.buttonX = this.browserGamepad.buttons[2].value;
  40390. this.buttonY = this.browserGamepad.buttons[3].value;
  40391. this.buttonLB = this.browserGamepad.buttons[4].value;
  40392. this.buttonRB = this.browserGamepad.buttons[5].value;
  40393. this.leftTrigger = this.browserGamepad.buttons[6].value;
  40394. this.rightTrigger = this.browserGamepad.buttons[7].value;
  40395. this.buttonBack = this.browserGamepad.buttons[8].value;
  40396. this.buttonStart = this.browserGamepad.buttons[9].value;
  40397. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  40398. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  40399. this.dPadUp = this.browserGamepad.buttons[12].value;
  40400. this.dPadDown = this.browserGamepad.buttons[13].value;
  40401. this.dPadLeft = this.browserGamepad.buttons[14].value;
  40402. this.dPadRight = this.browserGamepad.buttons[15].value;
  40403. };
  40404. return Xbox360Pad;
  40405. })(Gamepad);
  40406. BABYLON.Xbox360Pad = Xbox360Pad;
  40407. })(BABYLON || (BABYLON = {}));
  40408. var BABYLON;
  40409. (function (BABYLON) {
  40410. // We're mainly based on the logic defined into the FreeCamera code
  40411. var GamepadCamera = (function (_super) {
  40412. __extends(GamepadCamera, _super);
  40413. //-- end properties for backward compatibility for inputs
  40414. function GamepadCamera(name, position, scene) {
  40415. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  40416. _super.call(this, name, position, scene);
  40417. }
  40418. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  40419. //-- Begin properties for backward compatibility for inputs
  40420. get: function () {
  40421. var gamepad = this.inputs.attached["gamepad"];
  40422. if (gamepad)
  40423. return gamepad.gamepadAngularSensibility;
  40424. },
  40425. set: function (value) {
  40426. var gamepad = this.inputs.attached["gamepad"];
  40427. if (gamepad)
  40428. gamepad.gamepadAngularSensibility = value;
  40429. },
  40430. enumerable: true,
  40431. configurable: true
  40432. });
  40433. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  40434. get: function () {
  40435. var gamepad = this.inputs.attached["gamepad"];
  40436. if (gamepad)
  40437. return gamepad.gamepadMoveSensibility;
  40438. },
  40439. set: function (value) {
  40440. var gamepad = this.inputs.attached["gamepad"];
  40441. if (gamepad)
  40442. gamepad.gamepadMoveSensibility = value;
  40443. },
  40444. enumerable: true,
  40445. configurable: true
  40446. });
  40447. GamepadCamera.prototype.getTypeName = function () {
  40448. return "GamepadCamera";
  40449. };
  40450. return GamepadCamera;
  40451. })(BABYLON.UniversalCamera);
  40452. BABYLON.GamepadCamera = GamepadCamera;
  40453. })(BABYLON || (BABYLON = {}));
  40454. var BABYLON;
  40455. (function (BABYLON) {
  40456. var Analyser = (function () {
  40457. function Analyser(scene) {
  40458. this.SMOOTHING = 0.75;
  40459. this.FFT_SIZE = 512;
  40460. this.BARGRAPHAMPLITUDE = 256;
  40461. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  40462. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  40463. this._scene = scene;
  40464. this._audioEngine = BABYLON.Engine.audioEngine;
  40465. if (this._audioEngine.canUseWebAudio) {
  40466. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  40467. this._webAudioAnalyser.minDecibels = -140;
  40468. this._webAudioAnalyser.maxDecibels = 0;
  40469. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40470. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40471. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  40472. }
  40473. }
  40474. Analyser.prototype.getFrequencyBinCount = function () {
  40475. if (this._audioEngine.canUseWebAudio) {
  40476. return this._webAudioAnalyser.frequencyBinCount;
  40477. }
  40478. else {
  40479. return 0;
  40480. }
  40481. };
  40482. Analyser.prototype.getByteFrequencyData = function () {
  40483. if (this._audioEngine.canUseWebAudio) {
  40484. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40485. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40486. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  40487. }
  40488. return this._byteFreqs;
  40489. };
  40490. Analyser.prototype.getByteTimeDomainData = function () {
  40491. if (this._audioEngine.canUseWebAudio) {
  40492. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40493. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40494. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  40495. }
  40496. return this._byteTime;
  40497. };
  40498. Analyser.prototype.getFloatFrequencyData = function () {
  40499. if (this._audioEngine.canUseWebAudio) {
  40500. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40501. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40502. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  40503. }
  40504. return this._floatFreqs;
  40505. };
  40506. Analyser.prototype.drawDebugCanvas = function () {
  40507. var _this = this;
  40508. if (this._audioEngine.canUseWebAudio) {
  40509. if (!this._debugCanvas) {
  40510. this._debugCanvas = document.createElement("canvas");
  40511. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  40512. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  40513. this._debugCanvas.style.position = "absolute";
  40514. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  40515. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  40516. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  40517. document.body.appendChild(this._debugCanvas);
  40518. this._registerFunc = function () {
  40519. _this.drawDebugCanvas();
  40520. };
  40521. this._scene.registerBeforeRender(this._registerFunc);
  40522. }
  40523. if (this._registerFunc) {
  40524. var workingArray = this.getByteFrequencyData();
  40525. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  40526. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  40527. // Draw the frequency domain chart.
  40528. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  40529. var value = workingArray[i];
  40530. var percent = value / this.BARGRAPHAMPLITUDE;
  40531. var height = this.DEBUGCANVASSIZE.height * percent;
  40532. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  40533. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  40534. var hue = i / this.getFrequencyBinCount() * 360;
  40535. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  40536. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  40537. }
  40538. }
  40539. }
  40540. };
  40541. Analyser.prototype.stopDebugCanvas = function () {
  40542. if (this._debugCanvas) {
  40543. this._scene.unregisterBeforeRender(this._registerFunc);
  40544. this._registerFunc = null;
  40545. document.body.removeChild(this._debugCanvas);
  40546. this._debugCanvas = null;
  40547. this._debugCanvasContext = null;
  40548. }
  40549. };
  40550. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  40551. if (this._audioEngine.canUseWebAudio) {
  40552. inputAudioNode.connect(this._webAudioAnalyser);
  40553. this._webAudioAnalyser.connect(outputAudioNode);
  40554. }
  40555. };
  40556. Analyser.prototype.dispose = function () {
  40557. if (this._audioEngine.canUseWebAudio) {
  40558. this._webAudioAnalyser.disconnect();
  40559. }
  40560. };
  40561. return Analyser;
  40562. })();
  40563. BABYLON.Analyser = Analyser;
  40564. })(BABYLON || (BABYLON = {}));
  40565. var BABYLON;
  40566. (function (BABYLON) {
  40567. var DepthRenderer = (function () {
  40568. function DepthRenderer(scene, type) {
  40569. var _this = this;
  40570. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  40571. this._viewMatrix = BABYLON.Matrix.Zero();
  40572. this._projectionMatrix = BABYLON.Matrix.Zero();
  40573. this._transformMatrix = BABYLON.Matrix.Zero();
  40574. this._worldViewProjection = BABYLON.Matrix.Zero();
  40575. this._scene = scene;
  40576. var engine = scene.getEngine();
  40577. // Render target
  40578. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  40579. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40580. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40581. this._depthMap.refreshRate = 1;
  40582. this._depthMap.renderParticles = false;
  40583. this._depthMap.renderList = null;
  40584. // set default depth value to 1.0 (far away)
  40585. this._depthMap.onClear = function (engine) {
  40586. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  40587. };
  40588. // Custom render function
  40589. var renderSubMesh = function (subMesh) {
  40590. var mesh = subMesh.getRenderingMesh();
  40591. var scene = _this._scene;
  40592. var engine = scene.getEngine();
  40593. // Culling
  40594. engine.setState(subMesh.getMaterial().backFaceCulling);
  40595. // Managing instances
  40596. var batch = mesh._getInstancesRenderList(subMesh._id);
  40597. if (batch.mustReturn) {
  40598. return;
  40599. }
  40600. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40601. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40602. engine.enableEffect(_this._effect);
  40603. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  40604. var material = subMesh.getMaterial();
  40605. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  40606. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  40607. // Alpha test
  40608. if (material && material.needAlphaTesting()) {
  40609. var alphaTexture = material.getAlphaTestTexture();
  40610. _this._effect.setTexture("diffuseSampler", alphaTexture);
  40611. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40612. }
  40613. // Bones
  40614. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40615. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40616. }
  40617. // Draw
  40618. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  40619. }
  40620. };
  40621. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  40622. var index;
  40623. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40624. renderSubMesh(opaqueSubMeshes.data[index]);
  40625. }
  40626. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40627. renderSubMesh(alphaTestSubMeshes.data[index]);
  40628. }
  40629. };
  40630. }
  40631. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  40632. var material = subMesh.getMaterial();
  40633. if (material.disableDepthWrite) {
  40634. return false;
  40635. }
  40636. var defines = [];
  40637. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40638. var mesh = subMesh.getMesh();
  40639. var scene = mesh.getScene();
  40640. // Alpha test
  40641. if (material && material.needAlphaTesting()) {
  40642. defines.push("#define ALPHATEST");
  40643. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40644. attribs.push(BABYLON.VertexBuffer.UVKind);
  40645. defines.push("#define UV1");
  40646. }
  40647. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40648. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40649. defines.push("#define UV2");
  40650. }
  40651. }
  40652. // Bones
  40653. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40654. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40655. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40656. if (mesh.numBoneInfluencers > 4) {
  40657. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40658. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40659. }
  40660. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40661. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40662. }
  40663. else {
  40664. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40665. }
  40666. // Instances
  40667. if (useInstances) {
  40668. defines.push("#define INSTANCES");
  40669. attribs.push("world0");
  40670. attribs.push("world1");
  40671. attribs.push("world2");
  40672. attribs.push("world3");
  40673. }
  40674. // Get correct effect
  40675. var join = defines.join("\n");
  40676. if (this._cachedDefines !== join) {
  40677. this._cachedDefines = join;
  40678. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  40679. }
  40680. return this._effect.isReady();
  40681. };
  40682. DepthRenderer.prototype.getDepthMap = function () {
  40683. return this._depthMap;
  40684. };
  40685. // Methods
  40686. DepthRenderer.prototype.dispose = function () {
  40687. this._depthMap.dispose();
  40688. };
  40689. return DepthRenderer;
  40690. })();
  40691. BABYLON.DepthRenderer = DepthRenderer;
  40692. })(BABYLON || (BABYLON = {}));
  40693. var BABYLON;
  40694. (function (BABYLON) {
  40695. var SSAORenderingPipeline = (function (_super) {
  40696. __extends(SSAORenderingPipeline, _super);
  40697. /**
  40698. * @constructor
  40699. * @param {string} name - The rendering pipeline name
  40700. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40701. * @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 }
  40702. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40703. */
  40704. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  40705. var _this = this;
  40706. _super.call(this, scene.getEngine(), name);
  40707. // Members
  40708. /**
  40709. * The PassPostProcess id in the pipeline that contains the original scene color
  40710. * @type {string}
  40711. */
  40712. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  40713. /**
  40714. * The SSAO PostProcess id in the pipeline
  40715. * @type {string}
  40716. */
  40717. this.SSAORenderEffect = "SSAORenderEffect";
  40718. /**
  40719. * The horizontal blur PostProcess id in the pipeline
  40720. * @type {string}
  40721. */
  40722. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  40723. /**
  40724. * The vertical blur PostProcess id in the pipeline
  40725. * @type {string}
  40726. */
  40727. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  40728. /**
  40729. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  40730. * @type {string}
  40731. */
  40732. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  40733. /**
  40734. * The output strength of the SSAO post-process. Default value is 1.0.
  40735. * @type {number}
  40736. */
  40737. this.totalStrength = 1.0;
  40738. /**
  40739. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  40740. * @type {number}
  40741. */
  40742. this.radius = 0.0001;
  40743. /**
  40744. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  40745. * Must not be equal to fallOff and superior to fallOff.
  40746. * Default value is 0.975
  40747. * @type {number}
  40748. */
  40749. this.area = 0.0075;
  40750. /**
  40751. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  40752. * Must not be equal to area and inferior to area.
  40753. * Default value is 0.0
  40754. * @type {number}
  40755. */
  40756. this.fallOff = 0.000001;
  40757. /**
  40758. * The base color of the SSAO post-process
  40759. * The final result is "base + ssao" between [0, 1]
  40760. * @type {number}
  40761. */
  40762. this.base = 0.5;
  40763. this._firstUpdate = true;
  40764. this._scene = scene;
  40765. // Set up assets
  40766. this._createRandomTexture();
  40767. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40768. var ssaoRatio = ratio.ssaoRatio || ratio;
  40769. var combineRatio = ratio.combineRatio || ratio;
  40770. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40771. this._createSSAOPostProcess(ssaoRatio);
  40772. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40773. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40774. this._createSSAOCombinePostProcess(combineRatio);
  40775. // Set up pipeline
  40776. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  40777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  40778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  40779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  40780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  40781. // Finish
  40782. scene.postProcessRenderPipelineManager.addPipeline(this);
  40783. if (cameras)
  40784. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40785. }
  40786. // Public Methods
  40787. /**
  40788. * Returns the horizontal blur PostProcess
  40789. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  40790. */
  40791. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  40792. return this._blurHPostProcess;
  40793. };
  40794. /**
  40795. * Returns the vertical blur PostProcess
  40796. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  40797. */
  40798. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  40799. return this._blurVPostProcess;
  40800. };
  40801. /**
  40802. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  40803. */
  40804. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40805. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40806. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40807. this._originalColorPostProcess = undefined;
  40808. this._ssaoPostProcess = undefined;
  40809. this._blurHPostProcess = undefined;
  40810. this._blurVPostProcess = undefined;
  40811. this._ssaoCombinePostProcess = undefined;
  40812. this._randomTexture.dispose();
  40813. if (disableDepthRender)
  40814. this._scene.disableDepthRenderer();
  40815. };
  40816. // Private Methods
  40817. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  40818. var _this = this;
  40819. var numSamples = 16;
  40820. var sampleSphere = [
  40821. 0.5381, 0.1856, -0.4319,
  40822. 0.1379, 0.2486, 0.4430,
  40823. 0.3371, 0.5679, -0.0057,
  40824. -0.6999, -0.0451, -0.0019,
  40825. 0.0689, -0.1598, -0.8547,
  40826. 0.0560, 0.0069, -0.1843,
  40827. -0.0146, 0.1402, 0.0762,
  40828. 0.0100, -0.1924, -0.0344,
  40829. -0.3577, -0.5301, -0.4358,
  40830. -0.3169, 0.1063, 0.0158,
  40831. 0.0103, -0.5869, 0.0046,
  40832. -0.0897, -0.4940, 0.3287,
  40833. 0.7119, -0.0154, -0.0918,
  40834. -0.0533, 0.0596, -0.5411,
  40835. 0.0352, -0.0631, 0.5460,
  40836. -0.4776, 0.2847, -0.0271
  40837. ];
  40838. var samplesFactor = 1.0 / numSamples;
  40839. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  40840. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  40841. "area", "fallOff", "base"
  40842. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  40843. this._ssaoPostProcess.onApply = function (effect) {
  40844. if (_this._firstUpdate) {
  40845. effect.setArray3("sampleSphere", sampleSphere);
  40846. effect.setFloat("samplesFactor", samplesFactor);
  40847. effect.setFloat("randTextureTiles", 4.0);
  40848. _this._firstUpdate = false;
  40849. }
  40850. effect.setFloat("totalStrength", _this.totalStrength);
  40851. effect.setFloat("radius", _this.radius);
  40852. effect.setFloat("area", _this.area);
  40853. effect.setFloat("fallOff", _this.fallOff);
  40854. effect.setFloat("base", _this.base);
  40855. effect.setTexture("textureSampler", _this._depthTexture);
  40856. effect.setTexture("randomSampler", _this._randomTexture);
  40857. };
  40858. };
  40859. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  40860. var _this = this;
  40861. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40862. this._ssaoCombinePostProcess.onApply = function (effect) {
  40863. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  40864. };
  40865. };
  40866. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  40867. var size = 512;
  40868. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40869. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40870. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40871. var context = this._randomTexture.getContext();
  40872. var rand = function (min, max) {
  40873. return Math.random() * (max - min) + min;
  40874. };
  40875. var randVector = BABYLON.Vector3.Zero();
  40876. for (var x = 0; x < size; x++) {
  40877. for (var y = 0; y < size; y++) {
  40878. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  40879. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  40880. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  40881. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  40882. context.fillRect(x, y, 1, 1);
  40883. }
  40884. }
  40885. this._randomTexture.update(false);
  40886. };
  40887. return SSAORenderingPipeline;
  40888. })(BABYLON.PostProcessRenderPipeline);
  40889. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  40890. })(BABYLON || (BABYLON = {}));
  40891. var BABYLON;
  40892. (function (BABYLON) {
  40893. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  40894. var VolumetricLightScatteringPostProcess = (function (_super) {
  40895. __extends(VolumetricLightScatteringPostProcess, _super);
  40896. /**
  40897. * @constructor
  40898. * @param {string} name - The post-process name
  40899. * @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)
  40900. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  40901. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  40902. * @param {number} samples - The post-process quality, default 100
  40903. * @param {number} samplingMode - The post-process filtering mode
  40904. * @param {BABYLON.Engine} engine - The babylon engine
  40905. * @param {boolean} reusable - If the post-process is reusable
  40906. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  40907. */
  40908. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  40909. var _this = this;
  40910. if (samples === void 0) { samples = 100; }
  40911. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40912. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  40913. this._screenCoordinates = BABYLON.Vector2.Zero();
  40914. /**
  40915. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  40916. * @type {Vector3}
  40917. */
  40918. this.customMeshPosition = BABYLON.Vector3.Zero();
  40919. /**
  40920. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  40921. * @type {boolean}
  40922. */
  40923. this.useCustomMeshPosition = false;
  40924. /**
  40925. * If the post-process should inverse the light scattering direction
  40926. * @type {boolean}
  40927. */
  40928. this.invert = true;
  40929. /**
  40930. * Array containing the excluded meshes not rendered in the internal pass
  40931. */
  40932. this.excludedMeshes = new Array();
  40933. /**
  40934. * Controls the overall intensity of the post-process
  40935. * @type {number}
  40936. */
  40937. this.exposure = 0.3;
  40938. /**
  40939. * Dissipates each sample's contribution in range [0, 1]
  40940. * @type {number}
  40941. */
  40942. this.decay = 0.96815;
  40943. /**
  40944. * Controls the overall intensity of each sample
  40945. * @type {number}
  40946. */
  40947. this.weight = 0.58767;
  40948. /**
  40949. * Controls the density of each sample
  40950. * @type {number}
  40951. */
  40952. this.density = 0.926;
  40953. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  40954. var engine = scene.getEngine();
  40955. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  40956. // Configure mesh
  40957. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  40958. // Configure
  40959. this._createPass(scene, ratio.passRatio || ratio);
  40960. this.onActivate = function (camera) {
  40961. if (!_this.isSupported) {
  40962. _this.dispose(camera);
  40963. }
  40964. _this.onActivate = null;
  40965. };
  40966. this.onApply = function (effect) {
  40967. _this._updateMeshScreenCoordinates(scene);
  40968. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  40969. effect.setFloat("exposure", _this.exposure);
  40970. effect.setFloat("decay", _this.decay);
  40971. effect.setFloat("weight", _this.weight);
  40972. effect.setFloat("density", _this.density);
  40973. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  40974. };
  40975. }
  40976. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  40977. get: function () {
  40978. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  40979. return false;
  40980. },
  40981. set: function (useDiffuseColor) {
  40982. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  40983. },
  40984. enumerable: true,
  40985. configurable: true
  40986. });
  40987. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  40988. var mesh = subMesh.getMesh();
  40989. // Render this.mesh as default
  40990. if (mesh === this.mesh) {
  40991. return mesh.material.isReady(mesh);
  40992. }
  40993. var defines = [];
  40994. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40995. var material = subMesh.getMaterial();
  40996. var needUV = false;
  40997. // Alpha test
  40998. if (material) {
  40999. if (material.needAlphaTesting()) {
  41000. defines.push("#define ALPHATEST");
  41001. }
  41002. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41003. attribs.push(BABYLON.VertexBuffer.UVKind);
  41004. defines.push("#define UV1");
  41005. }
  41006. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41007. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41008. defines.push("#define UV2");
  41009. }
  41010. }
  41011. // Bones
  41012. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41013. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41014. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41015. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41016. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41017. }
  41018. else {
  41019. defines.push("#define NUM_BONE_INFLUENCERS 0");
  41020. }
  41021. // Instances
  41022. if (useInstances) {
  41023. defines.push("#define INSTANCES");
  41024. attribs.push("world0");
  41025. attribs.push("world1");
  41026. attribs.push("world2");
  41027. attribs.push("world3");
  41028. }
  41029. // Get correct effect
  41030. var join = defines.join("\n");
  41031. if (this._cachedDefines !== join) {
  41032. this._cachedDefines = join;
  41033. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  41034. }
  41035. return this._volumetricLightScatteringPass.isReady();
  41036. };
  41037. /**
  41038. * Sets the new light position for light scattering effect
  41039. * @param {BABYLON.Vector3} The new custom light position
  41040. */
  41041. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  41042. this.customMeshPosition = position;
  41043. };
  41044. /**
  41045. * Returns the light position for light scattering effect
  41046. * @return {BABYLON.Vector3} The custom light position
  41047. */
  41048. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  41049. return this.customMeshPosition;
  41050. };
  41051. /**
  41052. * Disposes the internal assets and detaches the post-process from the camera
  41053. */
  41054. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  41055. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  41056. if (rttIndex !== -1) {
  41057. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  41058. }
  41059. this._volumetricLightScatteringRTT.dispose();
  41060. _super.prototype.dispose.call(this, camera);
  41061. };
  41062. /**
  41063. * Returns the render target texture used by the post-process
  41064. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  41065. */
  41066. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  41067. return this._volumetricLightScatteringRTT;
  41068. };
  41069. // Private methods
  41070. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  41071. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  41072. return true;
  41073. }
  41074. return false;
  41075. };
  41076. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  41077. var _this = this;
  41078. var engine = scene.getEngine();
  41079. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  41080. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41081. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41082. this._volumetricLightScatteringRTT.renderList = null;
  41083. this._volumetricLightScatteringRTT.renderParticles = false;
  41084. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  41085. // Custom render function for submeshes
  41086. var renderSubMesh = function (subMesh) {
  41087. var mesh = subMesh.getRenderingMesh();
  41088. if (_this._meshExcluded(mesh)) {
  41089. return;
  41090. }
  41091. var scene = mesh.getScene();
  41092. var engine = scene.getEngine();
  41093. // Culling
  41094. engine.setState(subMesh.getMaterial().backFaceCulling);
  41095. // Managing instances
  41096. var batch = mesh._getInstancesRenderList(subMesh._id);
  41097. if (batch.mustReturn) {
  41098. return;
  41099. }
  41100. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  41101. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  41102. var effect = _this._volumetricLightScatteringPass;
  41103. if (mesh === _this.mesh) {
  41104. effect = subMesh.getMaterial().getEffect();
  41105. }
  41106. engine.enableEffect(effect);
  41107. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  41108. if (mesh === _this.mesh) {
  41109. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  41110. }
  41111. else {
  41112. var material = subMesh.getMaterial();
  41113. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  41114. // Alpha test
  41115. if (material && material.needAlphaTesting()) {
  41116. var alphaTexture = material.getAlphaTestTexture();
  41117. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  41118. if (alphaTexture) {
  41119. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  41120. }
  41121. }
  41122. // Bones
  41123. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41124. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  41125. }
  41126. }
  41127. // Draw
  41128. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  41129. }
  41130. };
  41131. // Render target texture callbacks
  41132. var savedSceneClearColor;
  41133. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  41134. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  41135. savedSceneClearColor = scene.clearColor;
  41136. scene.clearColor = sceneClearColor;
  41137. };
  41138. this._volumetricLightScatteringRTT.onAfterRender = function () {
  41139. scene.clearColor = savedSceneClearColor;
  41140. };
  41141. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  41142. var engine = scene.getEngine();
  41143. var index;
  41144. for (index = 0; index < opaqueSubMeshes.length; index++) {
  41145. renderSubMesh(opaqueSubMeshes.data[index]);
  41146. }
  41147. engine.setAlphaTesting(true);
  41148. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  41149. renderSubMesh(alphaTestSubMeshes.data[index]);
  41150. }
  41151. engine.setAlphaTesting(false);
  41152. if (transparentSubMeshes.length) {
  41153. // Sort sub meshes
  41154. for (index = 0; index < transparentSubMeshes.length; index++) {
  41155. var submesh = transparentSubMeshes.data[index];
  41156. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  41157. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  41158. }
  41159. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  41160. sortedArray.sort(function (a, b) {
  41161. // Alpha index first
  41162. if (a._alphaIndex > b._alphaIndex) {
  41163. return 1;
  41164. }
  41165. if (a._alphaIndex < b._alphaIndex) {
  41166. return -1;
  41167. }
  41168. // Then distance to camera
  41169. if (a._distanceToCamera < b._distanceToCamera) {
  41170. return 1;
  41171. }
  41172. if (a._distanceToCamera > b._distanceToCamera) {
  41173. return -1;
  41174. }
  41175. return 0;
  41176. });
  41177. // Render sub meshes
  41178. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  41179. for (index = 0; index < sortedArray.length; index++) {
  41180. renderSubMesh(sortedArray[index]);
  41181. }
  41182. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41183. }
  41184. };
  41185. };
  41186. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  41187. var transform = scene.getTransformMatrix();
  41188. var meshPosition;
  41189. if (this.useCustomMeshPosition) {
  41190. meshPosition = this.customMeshPosition;
  41191. }
  41192. else if (this.attachedNode) {
  41193. meshPosition = this.attachedNode.position;
  41194. }
  41195. else {
  41196. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  41197. }
  41198. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  41199. this._screenCoordinates.x = pos.x / this._viewPort.width;
  41200. this._screenCoordinates.y = pos.y / this._viewPort.height;
  41201. if (this.invert)
  41202. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  41203. };
  41204. // Static methods
  41205. /**
  41206. * Creates a default mesh for the Volumeric Light Scattering post-process
  41207. * @param {string} The mesh name
  41208. * @param {BABYLON.Scene} The scene where to create the mesh
  41209. * @return {BABYLON.Mesh} the default mesh
  41210. */
  41211. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  41212. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  41213. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  41214. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  41215. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  41216. mesh.material = material;
  41217. return mesh;
  41218. };
  41219. __decorate([
  41220. BABYLON.serializeAsVector3()
  41221. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  41222. __decorate([
  41223. BABYLON.serialize()
  41224. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  41225. __decorate([
  41226. BABYLON.serialize()
  41227. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  41228. __decorate([
  41229. BABYLON.serializeAsMeshReference()
  41230. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  41231. __decorate([
  41232. BABYLON.serialize()
  41233. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  41234. __decorate([
  41235. BABYLON.serialize()
  41236. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  41237. __decorate([
  41238. BABYLON.serialize()
  41239. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  41240. __decorate([
  41241. BABYLON.serialize()
  41242. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  41243. __decorate([
  41244. BABYLON.serialize()
  41245. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  41246. return VolumetricLightScatteringPostProcess;
  41247. })(BABYLON.PostProcess);
  41248. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  41249. })(BABYLON || (BABYLON = {}));
  41250. // BABYLON.JS Chromatic Aberration GLSL Shader
  41251. // Author: Olivier Guyot
  41252. // Separates very slightly R, G and B colors on the edges of the screen
  41253. // Inspired by Francois Tarlier & Martins Upitis
  41254. var BABYLON;
  41255. (function (BABYLON) {
  41256. var LensRenderingPipeline = (function (_super) {
  41257. __extends(LensRenderingPipeline, _super);
  41258. /**
  41259. * @constructor
  41260. *
  41261. * Effect parameters are as follow:
  41262. * {
  41263. * chromatic_aberration: number; // from 0 to x (1 for realism)
  41264. * edge_blur: number; // from 0 to x (1 for realism)
  41265. * distortion: number; // from 0 to x (1 for realism)
  41266. * grain_amount: number; // from 0 to 1
  41267. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  41268. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  41269. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  41270. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  41271. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  41272. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  41273. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  41274. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  41275. * }
  41276. * Note: if an effect parameter is unset, effect is disabled
  41277. *
  41278. * @param {string} name - The rendering pipeline name
  41279. * @param {object} parameters - An object containing all parameters (see above)
  41280. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  41281. * @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)
  41282. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  41283. */
  41284. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  41285. var _this = this;
  41286. if (ratio === void 0) { ratio = 1.0; }
  41287. _super.call(this, scene.getEngine(), name);
  41288. // Lens effects can be of the following:
  41289. // - chromatic aberration (slight shift of RGB colors)
  41290. // - blur on the edge of the lens
  41291. // - lens distortion
  41292. // - depth-of-field blur & highlights enhancing
  41293. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  41294. // - grain effect (noise or custom texture)
  41295. // Two additional texture samplers are needed:
  41296. // - depth map (for depth-of-field)
  41297. // - grain texture
  41298. /**
  41299. * The chromatic aberration PostProcess id in the pipeline
  41300. * @type {string}
  41301. */
  41302. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  41303. /**
  41304. * The highlights enhancing PostProcess id in the pipeline
  41305. * @type {string}
  41306. */
  41307. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  41308. /**
  41309. * The depth-of-field PostProcess id in the pipeline
  41310. * @type {string}
  41311. */
  41312. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  41313. this._scene = scene;
  41314. // Fetch texture samplers
  41315. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  41316. if (parameters.grain_texture) {
  41317. this._grainTexture = parameters.grain_texture;
  41318. }
  41319. else {
  41320. this._createGrainTexture();
  41321. }
  41322. // save parameters
  41323. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  41324. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  41325. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  41326. this._distortion = parameters.distortion ? parameters.distortion : 0;
  41327. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  41328. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  41329. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  41330. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  41331. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  41332. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  41333. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  41334. // Create effects
  41335. this._createChromaticAberrationPostProcess(ratio);
  41336. this._createHighlightsPostProcess(ratio);
  41337. this._createDepthOfFieldPostProcess(ratio / 4);
  41338. // Set up pipeline
  41339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  41340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  41341. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  41342. if (this._highlightsGain === -1) {
  41343. this._disableEffect(this.HighlightsEnhancingEffect, null);
  41344. }
  41345. // Finish
  41346. scene.postProcessRenderPipelineManager.addPipeline(this);
  41347. if (cameras) {
  41348. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  41349. }
  41350. }
  41351. // public methods (self explanatory)
  41352. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  41353. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  41354. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  41355. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  41356. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  41357. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  41358. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  41359. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  41360. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  41361. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  41362. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  41363. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  41364. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  41365. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  41366. };
  41367. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  41368. this._highlightsPostProcess.updateEffect();
  41369. };
  41370. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  41371. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  41372. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  41373. this._highlightsGain = amount;
  41374. };
  41375. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  41376. if (this._highlightsGain === -1) {
  41377. this._highlightsGain = 1.0;
  41378. }
  41379. this._highlightsThreshold = amount;
  41380. };
  41381. LensRenderingPipeline.prototype.disableHighlights = function () {
  41382. this._highlightsGain = -1;
  41383. };
  41384. /**
  41385. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  41386. */
  41387. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  41388. if (disableDepthRender === void 0) { disableDepthRender = false; }
  41389. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  41390. this._chromaticAberrationPostProcess = undefined;
  41391. this._highlightsPostProcess = undefined;
  41392. this._depthOfFieldPostProcess = undefined;
  41393. this._grainTexture.dispose();
  41394. if (disableDepthRender)
  41395. this._scene.disableDepthRenderer();
  41396. };
  41397. // colors shifting and distortion
  41398. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  41399. var _this = this;
  41400. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  41401. [], // samplers
  41402. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  41403. this._chromaticAberrationPostProcess.onApply = function (effect) {
  41404. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  41405. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  41406. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  41407. };
  41408. };
  41409. // highlights enhancing
  41410. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  41411. var _this = this;
  41412. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  41413. [], // samplers
  41414. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  41415. this._highlightsPostProcess.onApply = function (effect) {
  41416. effect.setFloat('gain', _this._highlightsGain);
  41417. effect.setFloat('threshold', _this._highlightsThreshold);
  41418. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  41419. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  41420. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  41421. };
  41422. };
  41423. // colors shifting and distortion
  41424. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  41425. var _this = this;
  41426. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  41427. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  41428. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  41429. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  41430. this._depthOfFieldPostProcess.onApply = function (effect) {
  41431. effect.setTexture("depthSampler", _this._depthTexture);
  41432. effect.setTexture("grainSampler", _this._grainTexture);
  41433. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  41434. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  41435. effect.setFloat('grain_amount', _this._grainAmount);
  41436. effect.setBool('blur_noise', _this._blurNoise);
  41437. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  41438. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  41439. effect.setFloat('distortion', _this._distortion);
  41440. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  41441. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  41442. effect.setFloat('aperture', _this._dofAperture);
  41443. effect.setFloat('darken', _this._dofDarken);
  41444. effect.setFloat('edge_blur', _this._edgeBlur);
  41445. effect.setBool('highlights', (_this._highlightsGain !== -1));
  41446. effect.setFloat('near', _this._scene.activeCamera.minZ);
  41447. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  41448. };
  41449. };
  41450. // creates a black and white random noise texture, 512x512
  41451. LensRenderingPipeline.prototype._createGrainTexture = function () {
  41452. var size = 512;
  41453. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41454. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  41455. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  41456. var context = this._grainTexture.getContext();
  41457. var rand = function (min, max) {
  41458. return Math.random() * (max - min) + min;
  41459. };
  41460. var value;
  41461. for (var x = 0; x < size; x++) {
  41462. for (var y = 0; y < size; y++) {
  41463. value = Math.floor(rand(0.42, 0.58) * 255);
  41464. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  41465. context.fillRect(x, y, 1, 1);
  41466. }
  41467. }
  41468. this._grainTexture.update(false);
  41469. };
  41470. return LensRenderingPipeline;
  41471. })(BABYLON.PostProcessRenderPipeline);
  41472. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  41473. })(BABYLON || (BABYLON = {}));
  41474. //
  41475. // This post-process allows the modification of rendered colors by using
  41476. // a 'look-up table' (LUT). This effect is also called Color Grading.
  41477. //
  41478. // The object needs to be provided an url to a texture containing the color
  41479. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  41480. // Use an image editing software to tweak the LUT to match your needs.
  41481. //
  41482. // For an example of a color LUT, see here:
  41483. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  41484. // For explanations on color grading, see here:
  41485. // http://udn.epicgames.com/Three/ColorGrading.html
  41486. //
  41487. var BABYLON;
  41488. (function (BABYLON) {
  41489. var ColorCorrectionPostProcess = (function (_super) {
  41490. __extends(ColorCorrectionPostProcess, _super);
  41491. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  41492. var _this = this;
  41493. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  41494. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  41495. this._colorTableTexture.anisotropicFilteringLevel = 1;
  41496. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41497. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41498. this.onApply = function (effect) {
  41499. effect.setTexture("colorTable", _this._colorTableTexture);
  41500. };
  41501. }
  41502. return ColorCorrectionPostProcess;
  41503. })(BABYLON.PostProcess);
  41504. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  41505. })(BABYLON || (BABYLON = {}));
  41506. var BABYLON;
  41507. (function (BABYLON) {
  41508. var AnaglyphFreeCamera = (function (_super) {
  41509. __extends(AnaglyphFreeCamera, _super);
  41510. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  41511. _super.call(this, name, position, scene);
  41512. this.interaxialDistance = interaxialDistance;
  41513. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41514. }
  41515. AnaglyphFreeCamera.prototype.getTypeName = function () {
  41516. return "AnaglyphFreeCamera";
  41517. };
  41518. return AnaglyphFreeCamera;
  41519. })(BABYLON.FreeCamera);
  41520. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  41521. var AnaglyphArcRotateCamera = (function (_super) {
  41522. __extends(AnaglyphArcRotateCamera, _super);
  41523. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  41524. _super.call(this, name, alpha, beta, radius, target, scene);
  41525. this.interaxialDistance = interaxialDistance;
  41526. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41527. }
  41528. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  41529. return "AnaglyphArcRotateCamera";
  41530. };
  41531. return AnaglyphArcRotateCamera;
  41532. })(BABYLON.ArcRotateCamera);
  41533. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  41534. var AnaglyphGamepadCamera = (function (_super) {
  41535. __extends(AnaglyphGamepadCamera, _super);
  41536. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  41537. _super.call(this, name, position, scene);
  41538. this.interaxialDistance = interaxialDistance;
  41539. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41540. }
  41541. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  41542. return "AnaglyphGamepadCamera";
  41543. };
  41544. return AnaglyphGamepadCamera;
  41545. })(BABYLON.GamepadCamera);
  41546. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  41547. var AnaglyphUniversalCamera = (function (_super) {
  41548. __extends(AnaglyphUniversalCamera, _super);
  41549. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  41550. _super.call(this, name, position, scene);
  41551. this.interaxialDistance = interaxialDistance;
  41552. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  41553. }
  41554. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  41555. return "AnaglyphUniversalCamera";
  41556. };
  41557. return AnaglyphUniversalCamera;
  41558. })(BABYLON.UniversalCamera);
  41559. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  41560. var StereoscopicFreeCamera = (function (_super) {
  41561. __extends(StereoscopicFreeCamera, _super);
  41562. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41563. _super.call(this, name, position, scene);
  41564. this.interaxialDistance = interaxialDistance;
  41565. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41566. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41567. }
  41568. StereoscopicFreeCamera.prototype.getTypeName = function () {
  41569. return "StereoscopicFreeCamera";
  41570. };
  41571. return StereoscopicFreeCamera;
  41572. })(BABYLON.FreeCamera);
  41573. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  41574. var StereoscopicArcRotateCamera = (function (_super) {
  41575. __extends(StereoscopicArcRotateCamera, _super);
  41576. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  41577. _super.call(this, name, alpha, beta, radius, target, scene);
  41578. this.interaxialDistance = interaxialDistance;
  41579. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41580. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41581. }
  41582. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  41583. return "StereoscopicArcRotateCamera";
  41584. };
  41585. return StereoscopicArcRotateCamera;
  41586. })(BABYLON.ArcRotateCamera);
  41587. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  41588. var StereoscopicGamepadCamera = (function (_super) {
  41589. __extends(StereoscopicGamepadCamera, _super);
  41590. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41591. _super.call(this, name, position, scene);
  41592. this.interaxialDistance = interaxialDistance;
  41593. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41594. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41595. }
  41596. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  41597. return "StereoscopicGamepadCamera";
  41598. };
  41599. return StereoscopicGamepadCamera;
  41600. })(BABYLON.GamepadCamera);
  41601. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  41602. var StereoscopicUniversalCamera = (function (_super) {
  41603. __extends(StereoscopicUniversalCamera, _super);
  41604. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  41605. _super.call(this, name, position, scene);
  41606. this.interaxialDistance = interaxialDistance;
  41607. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  41608. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  41609. }
  41610. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  41611. return "StereoscopicUniversalCamera";
  41612. };
  41613. return StereoscopicUniversalCamera;
  41614. })(BABYLON.UniversalCamera);
  41615. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  41616. })(BABYLON || (BABYLON = {}));
  41617. var BABYLON;
  41618. (function (BABYLON) {
  41619. var HDRRenderingPipeline = (function (_super) {
  41620. __extends(HDRRenderingPipeline, _super);
  41621. /**
  41622. * @constructor
  41623. * @param {string} name - The rendering pipeline name
  41624. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  41625. * @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)
  41626. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  41627. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  41628. */
  41629. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  41630. var _this = this;
  41631. if (originalPostProcess === void 0) { originalPostProcess = null; }
  41632. _super.call(this, scene.getEngine(), name);
  41633. /**
  41634. * Public members
  41635. */
  41636. // Gaussian Blur
  41637. /**
  41638. * Gaussian blur coefficient
  41639. * @type {number}
  41640. */
  41641. this.gaussCoeff = 0.3;
  41642. /**
  41643. * Gaussian blur mean
  41644. * @type {number}
  41645. */
  41646. this.gaussMean = 1.0;
  41647. /**
  41648. * Gaussian blur standard deviation
  41649. * @type {number}
  41650. */
  41651. this.gaussStandDev = 0.8;
  41652. /**
  41653. * Gaussian blur multiplier. Multiplies the blur effect
  41654. * @type {number}
  41655. */
  41656. this.gaussMultiplier = 4.0;
  41657. // HDR
  41658. /**
  41659. * Exposure, controls the overall intensity of the pipeline
  41660. * @type {number}
  41661. */
  41662. this.exposure = 1.0;
  41663. /**
  41664. * Minimum luminance that the post-process can output. Luminance is >= 0
  41665. * @type {number}
  41666. */
  41667. this.minimumLuminance = 1.0;
  41668. /**
  41669. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  41670. * @type {number}
  41671. */
  41672. this.maximumLuminance = 1e20;
  41673. /**
  41674. * Increase rate for luminance: eye adaptation speed to dark
  41675. * @type {number}
  41676. */
  41677. this.luminanceIncreaserate = 0.5;
  41678. /**
  41679. * Decrease rate for luminance: eye adaptation speed to bright
  41680. * @type {number}
  41681. */
  41682. this.luminanceDecreaseRate = 0.5;
  41683. // Bright pass
  41684. /**
  41685. * Minimum luminance needed to compute HDR
  41686. * @type {number}
  41687. */
  41688. this.brightThreshold = 0.8;
  41689. this._needUpdate = true;
  41690. this._scene = scene;
  41691. // Bright pass
  41692. this._createBrightPassPostProcess(scene, ratio);
  41693. // Down sample X4
  41694. this._createDownSampleX4PostProcess(scene, ratio);
  41695. // Create gaussian blur post-processes
  41696. this._createGaussianBlurPostProcess(scene, ratio);
  41697. // Texture adder
  41698. this._createTextureAdderPostProcess(scene, ratio);
  41699. // Luminance generator
  41700. this._createLuminanceGeneratorPostProcess(scene);
  41701. // HDR
  41702. this._createHDRPostProcess(scene, ratio);
  41703. // Pass postprocess
  41704. if (originalPostProcess === null) {
  41705. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  41706. }
  41707. else {
  41708. this._originalPostProcess = originalPostProcess;
  41709. }
  41710. // Configure pipeline
  41711. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  41712. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  41713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  41714. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  41715. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  41716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  41717. var addDownSamplerPostProcess = function (id) {
  41718. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  41719. };
  41720. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  41721. addDownSamplerPostProcess(i);
  41722. }
  41723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  41724. // Finish
  41725. scene.postProcessRenderPipelineManager.addPipeline(this);
  41726. if (cameras !== null) {
  41727. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  41728. }
  41729. this.update();
  41730. }
  41731. /**
  41732. * Tells the pipeline to update its post-processes
  41733. */
  41734. HDRRenderingPipeline.prototype.update = function () {
  41735. this._needUpdate = true;
  41736. };
  41737. /**
  41738. * Returns the current calculated luminance
  41739. */
  41740. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  41741. return this._hdrCurrentLuminance;
  41742. };
  41743. /**
  41744. * Returns the currently drawn luminance
  41745. */
  41746. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  41747. return this._hdrOutputLuminance;
  41748. };
  41749. /**
  41750. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  41751. */
  41752. HDRRenderingPipeline.prototype.dispose = function () {
  41753. this._originalPostProcess = undefined;
  41754. this._brightPassPostProcess = undefined;
  41755. this._downSampleX4PostProcess = undefined;
  41756. this._guassianBlurHPostProcess = undefined;
  41757. this._guassianBlurVPostProcess = undefined;
  41758. this._textureAdderPostProcess = undefined;
  41759. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  41760. this._downSamplePostProcesses[i] = undefined;
  41761. }
  41762. this._hdrPostProcess = undefined;
  41763. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  41764. };
  41765. /**
  41766. * Creates the HDR post-process and computes the luminance adaptation
  41767. */
  41768. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  41769. var _this = this;
  41770. var hdrLastLuminance = 0.0;
  41771. this._hdrOutputLuminance = -1.0;
  41772. this._hdrCurrentLuminance = 1.0;
  41773. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  41774. this._hdrPostProcess.onApply = function (effect) {
  41775. if (_this._hdrOutputLuminance < 0.0) {
  41776. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  41777. }
  41778. else {
  41779. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  41780. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  41781. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  41782. }
  41783. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  41784. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  41785. }
  41786. else {
  41787. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  41788. }
  41789. }
  41790. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  41791. hdrLastLuminance += scene.getEngine().getDeltaTime();
  41792. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  41793. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  41794. effect.setFloat("exposure", _this.exposure);
  41795. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  41796. _this._needUpdate = false;
  41797. };
  41798. };
  41799. /**
  41800. * Texture Adder post-process
  41801. */
  41802. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  41803. var _this = this;
  41804. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  41805. this._textureAdderPostProcess.onApply = function (effect) {
  41806. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  41807. };
  41808. };
  41809. /**
  41810. * Down sample X4 post-process
  41811. */
  41812. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  41813. var _this = this;
  41814. var downSampleX4Offsets = new Array(32);
  41815. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  41816. this._downSampleX4PostProcess.onApply = function (effect) {
  41817. if (_this._needUpdate) {
  41818. var id = 0;
  41819. for (var i = -2; i < 2; i++) {
  41820. for (var j = -2; j < 2; j++) {
  41821. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  41822. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  41823. id += 2;
  41824. }
  41825. }
  41826. }
  41827. effect.setArray2("dsOffsets", downSampleX4Offsets);
  41828. };
  41829. };
  41830. /**
  41831. * Bright pass post-process
  41832. */
  41833. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  41834. var _this = this;
  41835. var brightOffsets = new Array(8);
  41836. var brightPassCallback = function (effect) {
  41837. if (_this._needUpdate) {
  41838. var sU = (1.0 / _this._brightPassPostProcess.width);
  41839. var sV = (1.0 / _this._brightPassPostProcess.height);
  41840. brightOffsets[0] = -0.5 * sU;
  41841. brightOffsets[1] = 0.5 * sV;
  41842. brightOffsets[2] = 0.5 * sU;
  41843. brightOffsets[3] = 0.5 * sV;
  41844. brightOffsets[4] = -0.5 * sU;
  41845. brightOffsets[5] = -0.5 * sV;
  41846. brightOffsets[6] = 0.5 * sU;
  41847. brightOffsets[7] = -0.5 * sV;
  41848. }
  41849. effect.setArray2("dsOffsets", brightOffsets);
  41850. effect.setFloat("brightThreshold", _this.brightThreshold);
  41851. };
  41852. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  41853. this._brightPassPostProcess.onApply = brightPassCallback;
  41854. };
  41855. /**
  41856. * Luminance generator. Creates the luminance post-process and down sample post-processes
  41857. */
  41858. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  41859. var _this = this;
  41860. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  41861. var luminanceOffsets = new Array(8);
  41862. var downSampleOffsets = new Array(18);
  41863. var halfDestPixelSize;
  41864. this._downSamplePostProcesses = new Array(lumSteps);
  41865. // Utils for luminance
  41866. var luminanceUpdateSourceOffsets = function (width, height) {
  41867. var sU = (1.0 / width);
  41868. var sV = (1.0 / height);
  41869. luminanceOffsets[0] = -0.5 * sU;
  41870. luminanceOffsets[1] = 0.5 * sV;
  41871. luminanceOffsets[2] = 0.5 * sU;
  41872. luminanceOffsets[3] = 0.5 * sV;
  41873. luminanceOffsets[4] = -0.5 * sU;
  41874. luminanceOffsets[5] = -0.5 * sV;
  41875. luminanceOffsets[6] = 0.5 * sU;
  41876. luminanceOffsets[7] = -0.5 * sV;
  41877. };
  41878. var luminanceUpdateDestOffsets = function (width, height) {
  41879. var id = 0;
  41880. for (var x = -1; x < 2; x++) {
  41881. for (var y = -1; y < 2; y++) {
  41882. downSampleOffsets[id] = (x) / width;
  41883. downSampleOffsets[id + 1] = (y) / height;
  41884. id += 2;
  41885. }
  41886. }
  41887. };
  41888. // Luminance callback
  41889. var luminanceCallback = function (effect) {
  41890. if (_this._needUpdate) {
  41891. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  41892. }
  41893. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  41894. effect.setArray2("lumOffsets", luminanceOffsets);
  41895. };
  41896. // Down sample callbacks
  41897. var downSampleCallback = function (indice) {
  41898. var i = indice;
  41899. return function (effect) {
  41900. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  41901. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  41902. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  41903. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  41904. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  41905. effect.setArray2("dsOffsets", downSampleOffsets);
  41906. };
  41907. };
  41908. var downSampleAfterRenderCallback = function (effect) {
  41909. // Unpack result
  41910. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  41911. 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);
  41912. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  41913. };
  41914. // Create luminance post-process
  41915. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  41916. 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);
  41917. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  41918. // Create down sample post-processes
  41919. for (var i = lumSteps - 2; i >= 0; i--) {
  41920. var length = Math.pow(3, i);
  41921. ratio = { width: length, height: length };
  41922. var defines = "#define DOWN_SAMPLE\n";
  41923. if (i === 0) {
  41924. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  41925. }
  41926. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  41927. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  41928. if (i === 0) {
  41929. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  41930. }
  41931. }
  41932. };
  41933. /**
  41934. * Gaussian blur post-processes. Horizontal and Vertical
  41935. */
  41936. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  41937. var _this = this;
  41938. var blurOffsetsW = new Array(9);
  41939. var blurOffsetsH = new Array(9);
  41940. var blurWeights = new Array(9);
  41941. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  41942. // Utils for gaussian blur
  41943. var calculateBlurOffsets = function (height) {
  41944. var lastOutputDimensions = {
  41945. width: scene.getEngine().getRenderWidth(),
  41946. height: scene.getEngine().getRenderHeight()
  41947. };
  41948. for (var i = 0; i < 9; i++) {
  41949. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  41950. if (height) {
  41951. blurOffsetsH[i] = value;
  41952. }
  41953. else {
  41954. blurOffsetsW[i] = value;
  41955. }
  41956. }
  41957. };
  41958. var calculateWeights = function () {
  41959. var x = 0.0;
  41960. for (var i = 0; i < 9; i++) {
  41961. x = (i - 4.0) / 4.0;
  41962. 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));
  41963. }
  41964. };
  41965. // Callback
  41966. var gaussianBlurCallback = function (height) {
  41967. return function (effect) {
  41968. if (_this._needUpdate) {
  41969. calculateWeights();
  41970. calculateBlurOffsets(height);
  41971. }
  41972. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  41973. effect.setArray("blurWeights", blurWeights);
  41974. effect.setFloat("multiplier", _this.gaussMultiplier);
  41975. };
  41976. };
  41977. // Create horizontal gaussian blur post-processes
  41978. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  41979. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  41980. // Create vertical gaussian blur post-process
  41981. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  41982. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  41983. };
  41984. // Luminance generator
  41985. HDRRenderingPipeline.LUM_STEPS = 6;
  41986. return HDRRenderingPipeline;
  41987. })(BABYLON.PostProcessRenderPipeline);
  41988. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  41989. })(BABYLON || (BABYLON = {}));
  41990. var BABYLON;
  41991. (function (BABYLON) {
  41992. var FaceAdjacencies = (function () {
  41993. function FaceAdjacencies() {
  41994. this.edges = new Array();
  41995. this.edgesConnectedCount = 0;
  41996. }
  41997. return FaceAdjacencies;
  41998. })();
  41999. var EdgesRenderer = (function () {
  42000. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  42001. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  42002. if (epsilon === void 0) { epsilon = 0.95; }
  42003. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  42004. this.edgesWidthScalerForOrthographic = 1000.0;
  42005. this.edgesWidthScalerForPerspective = 50.0;
  42006. this._linesPositions = new Array();
  42007. this._linesNormals = new Array();
  42008. this._linesIndices = new Array();
  42009. this._buffers = new Array();
  42010. this._checkVerticesInsteadOfIndices = false;
  42011. this._source = source;
  42012. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  42013. this._epsilon = epsilon;
  42014. this._prepareRessources();
  42015. this._generateEdgesLines();
  42016. }
  42017. EdgesRenderer.prototype._prepareRessources = function () {
  42018. if (this._lineShader) {
  42019. return;
  42020. }
  42021. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  42022. attributes: ["position", "normal"],
  42023. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  42024. });
  42025. this._lineShader.disableDepthWrite = true;
  42026. this._lineShader.backFaceCulling = false;
  42027. };
  42028. EdgesRenderer.prototype.dispose = function () {
  42029. this._vb0.dispose();
  42030. this._vb1.dispose();
  42031. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  42032. this._lineShader.dispose();
  42033. };
  42034. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  42035. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  42036. return 0;
  42037. }
  42038. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  42039. return 1;
  42040. }
  42041. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  42042. return 2;
  42043. }
  42044. return -1;
  42045. };
  42046. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  42047. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  42048. return 0;
  42049. }
  42050. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  42051. return 1;
  42052. }
  42053. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  42054. return 2;
  42055. }
  42056. return -1;
  42057. };
  42058. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  42059. var needToCreateLine;
  42060. if (edge === undefined) {
  42061. needToCreateLine = true;
  42062. }
  42063. else {
  42064. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  42065. needToCreateLine = dotProduct < this._epsilon;
  42066. }
  42067. if (needToCreateLine) {
  42068. var offset = this._linesPositions.length / 3;
  42069. var normal = p0.subtract(p1);
  42070. normal.normalize();
  42071. // Positions
  42072. this._linesPositions.push(p0.x);
  42073. this._linesPositions.push(p0.y);
  42074. this._linesPositions.push(p0.z);
  42075. this._linesPositions.push(p0.x);
  42076. this._linesPositions.push(p0.y);
  42077. this._linesPositions.push(p0.z);
  42078. this._linesPositions.push(p1.x);
  42079. this._linesPositions.push(p1.y);
  42080. this._linesPositions.push(p1.z);
  42081. this._linesPositions.push(p1.x);
  42082. this._linesPositions.push(p1.y);
  42083. this._linesPositions.push(p1.z);
  42084. // Normals
  42085. this._linesNormals.push(p1.x);
  42086. this._linesNormals.push(p1.y);
  42087. this._linesNormals.push(p1.z);
  42088. this._linesNormals.push(-1);
  42089. this._linesNormals.push(p1.x);
  42090. this._linesNormals.push(p1.y);
  42091. this._linesNormals.push(p1.z);
  42092. this._linesNormals.push(1);
  42093. this._linesNormals.push(p0.x);
  42094. this._linesNormals.push(p0.y);
  42095. this._linesNormals.push(p0.z);
  42096. this._linesNormals.push(-1);
  42097. this._linesNormals.push(p0.x);
  42098. this._linesNormals.push(p0.y);
  42099. this._linesNormals.push(p0.z);
  42100. this._linesNormals.push(1);
  42101. // Indices
  42102. this._linesIndices.push(offset);
  42103. this._linesIndices.push(offset + 1);
  42104. this._linesIndices.push(offset + 2);
  42105. this._linesIndices.push(offset);
  42106. this._linesIndices.push(offset + 2);
  42107. this._linesIndices.push(offset + 3);
  42108. }
  42109. };
  42110. EdgesRenderer.prototype._generateEdgesLines = function () {
  42111. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42112. var indices = this._source.getIndices();
  42113. // First let's find adjacencies
  42114. var adjacencies = new Array();
  42115. var faceNormals = new Array();
  42116. var index;
  42117. var faceAdjacencies;
  42118. // Prepare faces
  42119. for (index = 0; index < indices.length; index += 3) {
  42120. faceAdjacencies = new FaceAdjacencies();
  42121. var p0Index = indices[index];
  42122. var p1Index = indices[index + 1];
  42123. var p2Index = indices[index + 2];
  42124. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  42125. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  42126. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  42127. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  42128. faceNormal.normalize();
  42129. faceNormals.push(faceNormal);
  42130. adjacencies.push(faceAdjacencies);
  42131. }
  42132. // Scan
  42133. for (index = 0; index < adjacencies.length; index++) {
  42134. faceAdjacencies = adjacencies[index];
  42135. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  42136. var otherFaceAdjacencies = adjacencies[otherIndex];
  42137. if (faceAdjacencies.edgesConnectedCount === 3) {
  42138. break;
  42139. }
  42140. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  42141. continue;
  42142. }
  42143. var otherP0 = indices[otherIndex * 3];
  42144. var otherP1 = indices[otherIndex * 3 + 1];
  42145. var otherP2 = indices[otherIndex * 3 + 2];
  42146. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  42147. var otherEdgeIndex;
  42148. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  42149. continue;
  42150. }
  42151. switch (edgeIndex) {
  42152. case 0:
  42153. if (this._checkVerticesInsteadOfIndices) {
  42154. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  42155. }
  42156. else {
  42157. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  42158. }
  42159. break;
  42160. case 1:
  42161. if (this._checkVerticesInsteadOfIndices) {
  42162. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  42163. }
  42164. else {
  42165. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  42166. }
  42167. break;
  42168. case 2:
  42169. if (this._checkVerticesInsteadOfIndices) {
  42170. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  42171. }
  42172. else {
  42173. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  42174. }
  42175. break;
  42176. }
  42177. if (otherEdgeIndex === -1) {
  42178. continue;
  42179. }
  42180. faceAdjacencies.edges[edgeIndex] = otherIndex;
  42181. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  42182. faceAdjacencies.edgesConnectedCount++;
  42183. otherFaceAdjacencies.edgesConnectedCount++;
  42184. if (faceAdjacencies.edgesConnectedCount === 3) {
  42185. break;
  42186. }
  42187. }
  42188. }
  42189. }
  42190. // Create lines
  42191. for (index = 0; index < adjacencies.length; index++) {
  42192. // 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
  42193. var current = adjacencies[index];
  42194. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  42195. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  42196. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  42197. }
  42198. // Merge into a single mesh
  42199. var engine = this._source.getScene().getEngine();
  42200. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  42201. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  42202. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  42203. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  42204. this._ib = engine.createIndexBuffer(this._linesIndices);
  42205. this._indicesCount = this._linesIndices.length;
  42206. };
  42207. EdgesRenderer.prototype.render = function () {
  42208. if (!this._lineShader.isReady()) {
  42209. return;
  42210. }
  42211. var scene = this._source.getScene();
  42212. var engine = scene.getEngine();
  42213. this._lineShader._preBind();
  42214. // VBOs
  42215. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  42216. scene.resetCachedMaterial();
  42217. this._lineShader.setColor4("color", this._source.edgesColor);
  42218. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  42219. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  42220. }
  42221. else {
  42222. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  42223. }
  42224. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  42225. this._lineShader.bind(this._source.getWorldMatrix());
  42226. // Draw order
  42227. engine.draw(true, 0, this._indicesCount);
  42228. this._lineShader.unbind();
  42229. engine.setDepthWrite(true);
  42230. };
  42231. return EdgesRenderer;
  42232. })();
  42233. BABYLON.EdgesRenderer = EdgesRenderer;
  42234. })(BABYLON || (BABYLON = {}));
  42235. var BABYLON;
  42236. (function (BABYLON) {
  42237. (function (TonemappingOperator) {
  42238. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  42239. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  42240. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  42241. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  42242. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  42243. var TonemappingOperator = BABYLON.TonemappingOperator;
  42244. ;
  42245. var TonemapPostProcess = (function (_super) {
  42246. __extends(TonemapPostProcess, _super);
  42247. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  42248. var _this = this;
  42249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  42250. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  42251. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  42252. this._operator = _operator;
  42253. this.exposureAdjustment = exposureAdjustment;
  42254. var defines = "#define ";
  42255. if (this._operator === TonemappingOperator.Hable)
  42256. defines += "HABLE_TONEMAPPING";
  42257. else if (this._operator === TonemappingOperator.Reinhard)
  42258. defines += "REINHARD_TONEMAPPING";
  42259. else if (this._operator === TonemappingOperator.HejiDawson)
  42260. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  42261. else if (this._operator === TonemappingOperator.Photographic)
  42262. defines += "PHOTOGRAPHIC_TONEMAPPING";
  42263. //sadly a second call to create the effect.
  42264. this.updateEffect(defines);
  42265. this.onApply = function (effect) {
  42266. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  42267. };
  42268. }
  42269. return TonemapPostProcess;
  42270. })(BABYLON.PostProcess);
  42271. BABYLON.TonemapPostProcess = TonemapPostProcess;
  42272. })(BABYLON || (BABYLON = {}));
  42273. var BABYLON;
  42274. (function (BABYLON) {
  42275. var ReflectionProbe = (function () {
  42276. function ReflectionProbe(name, size, scene, generateMipMaps) {
  42277. var _this = this;
  42278. if (generateMipMaps === void 0) { generateMipMaps = true; }
  42279. this.name = name;
  42280. this._viewMatrix = BABYLON.Matrix.Identity();
  42281. this._target = BABYLON.Vector3.Zero();
  42282. this._add = BABYLON.Vector3.Zero();
  42283. this.invertYAxis = false;
  42284. this.position = BABYLON.Vector3.Zero();
  42285. this._scene = scene;
  42286. this._scene.reflectionProbes.push(this);
  42287. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  42288. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  42289. switch (faceIndex) {
  42290. case 0:
  42291. _this._add.copyFromFloats(1, 0, 0);
  42292. break;
  42293. case 1:
  42294. _this._add.copyFromFloats(-1, 0, 0);
  42295. break;
  42296. case 2:
  42297. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  42298. break;
  42299. case 3:
  42300. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  42301. break;
  42302. case 4:
  42303. _this._add.copyFromFloats(0, 0, 1);
  42304. break;
  42305. case 5:
  42306. _this._add.copyFromFloats(0, 0, -1);
  42307. break;
  42308. }
  42309. if (_this._attachedMesh) {
  42310. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  42311. }
  42312. _this.position.addToRef(_this._add, _this._target);
  42313. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  42314. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  42315. };
  42316. this._renderTargetTexture.onAfterUnbind = function () {
  42317. scene.updateTransformMatrix(true);
  42318. };
  42319. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  42320. }
  42321. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  42322. get: function () {
  42323. return this._renderTargetTexture.refreshRate;
  42324. },
  42325. set: function (value) {
  42326. this._renderTargetTexture.refreshRate = value;
  42327. },
  42328. enumerable: true,
  42329. configurable: true
  42330. });
  42331. ReflectionProbe.prototype.getScene = function () {
  42332. return this._scene;
  42333. };
  42334. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  42335. get: function () {
  42336. return this._renderTargetTexture;
  42337. },
  42338. enumerable: true,
  42339. configurable: true
  42340. });
  42341. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  42342. get: function () {
  42343. return this._renderTargetTexture.renderList;
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  42349. this._attachedMesh = mesh;
  42350. };
  42351. ReflectionProbe.prototype.dispose = function () {
  42352. var index = this._scene.reflectionProbes.indexOf(this);
  42353. if (index !== -1) {
  42354. // Remove from the scene if found
  42355. this._scene.reflectionProbes.splice(index, 1);
  42356. }
  42357. if (this._renderTargetTexture) {
  42358. this._renderTargetTexture.dispose();
  42359. this._renderTargetTexture = null;
  42360. }
  42361. };
  42362. return ReflectionProbe;
  42363. })();
  42364. BABYLON.ReflectionProbe = ReflectionProbe;
  42365. })(BABYLON || (BABYLON = {}));
  42366. var BABYLON;
  42367. (function (BABYLON) {
  42368. var SolidParticle = (function () {
  42369. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  42370. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  42371. this.position = BABYLON.Vector3.Zero(); // position
  42372. this.rotation = BABYLON.Vector3.Zero(); // rotation
  42373. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  42374. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  42375. this.velocity = BABYLON.Vector3.Zero(); // velocity
  42376. this.alive = true; // alive
  42377. this.idx = particleIndex;
  42378. this._pos = positionIndex;
  42379. this._model = model;
  42380. this.shapeId = shapeId;
  42381. this.idxInShape = idxInShape;
  42382. }
  42383. Object.defineProperty(SolidParticle.prototype, "scale", {
  42384. //legacy support, changed scale to scaling
  42385. get: function () {
  42386. return this.scaling;
  42387. },
  42388. set: function (scale) {
  42389. this.scaling = scale;
  42390. },
  42391. enumerable: true,
  42392. configurable: true
  42393. });
  42394. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  42395. //legacy support, changed quaternion to rotationQuaternion
  42396. get: function () {
  42397. return this.rotationQuaternion;
  42398. },
  42399. set: function (q) {
  42400. this.rotationQuaternion = q;
  42401. },
  42402. enumerable: true,
  42403. configurable: true
  42404. });
  42405. return SolidParticle;
  42406. })();
  42407. BABYLON.SolidParticle = SolidParticle;
  42408. var ModelShape = (function () {
  42409. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  42410. this.shapeID = id;
  42411. this._shape = shape;
  42412. this._shapeUV = shapeUV;
  42413. this._positionFunction = posFunction;
  42414. this._vertexFunction = vtxFunction;
  42415. }
  42416. return ModelShape;
  42417. })();
  42418. BABYLON.ModelShape = ModelShape;
  42419. })(BABYLON || (BABYLON = {}));
  42420. var BABYLON;
  42421. (function (BABYLON) {
  42422. /**
  42423. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  42424. */
  42425. var SolidParticleSystem = (function () {
  42426. /**
  42427. * Creates a SPS (Solid Particle System) object.
  42428. * `name` (String) is the SPS name, this will be the underlying mesh name.
  42429. * `scene` (Scene) is the scene in which the SPS is added.
  42430. * `updatableè (default true) : if the SPS must be updatable or immutable.
  42431. * `isPickable` (default false) : if the solid particles must be pickable.
  42432. */
  42433. function SolidParticleSystem(name, scene, options) {
  42434. // public members
  42435. /**
  42436. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  42437. * Example : var p = SPS.particles[i];
  42438. */
  42439. this.particles = new Array();
  42440. /**
  42441. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  42442. */
  42443. this.nbParticles = 0;
  42444. /**
  42445. * If the particles must ever face the camera (default false). Useful for planar particles.
  42446. */
  42447. this.billboard = false;
  42448. /**
  42449. * This a counter ofr your own usage. It's not set by any SPS functions.
  42450. */
  42451. this.counter = 0;
  42452. /**
  42453. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  42454. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  42455. */
  42456. this.vars = {};
  42457. this._positions = new Array();
  42458. this._indices = new Array();
  42459. this._normals = new Array();
  42460. this._colors = new Array();
  42461. this._uvs = new Array();
  42462. this._index = 0; // indices index
  42463. this._updatable = true;
  42464. this._pickable = false;
  42465. this._isVisibilityBoxLocked = false;
  42466. this._alwaysVisible = false;
  42467. this._shapeCounter = 0;
  42468. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  42469. this._color = new BABYLON.Color4(0, 0, 0, 0);
  42470. this._computeParticleColor = true;
  42471. this._computeParticleTexture = true;
  42472. this._computeParticleRotation = true;
  42473. this._computeParticleVertex = false;
  42474. this._computeBoundingBox = false;
  42475. this._cam_axisZ = BABYLON.Vector3.Zero();
  42476. this._cam_axisY = BABYLON.Vector3.Zero();
  42477. this._cam_axisX = BABYLON.Vector3.Zero();
  42478. this._axisX = BABYLON.Axis.X;
  42479. this._axisY = BABYLON.Axis.Y;
  42480. this._axisZ = BABYLON.Axis.Z;
  42481. this._fakeCamPos = BABYLON.Vector3.Zero();
  42482. this._rotMatrix = new BABYLON.Matrix();
  42483. this._invertMatrix = new BABYLON.Matrix();
  42484. this._rotated = BABYLON.Vector3.Zero();
  42485. this._quaternion = new BABYLON.Quaternion();
  42486. this._vertex = BABYLON.Vector3.Zero();
  42487. this._normal = BABYLON.Vector3.Zero();
  42488. this._yaw = 0.0;
  42489. this._pitch = 0.0;
  42490. this._roll = 0.0;
  42491. this._halfroll = 0.0;
  42492. this._halfpitch = 0.0;
  42493. this._halfyaw = 0.0;
  42494. this._sinRoll = 0.0;
  42495. this._cosRoll = 0.0;
  42496. this._sinPitch = 0.0;
  42497. this._cosPitch = 0.0;
  42498. this._sinYaw = 0.0;
  42499. this._cosYaw = 0.0;
  42500. this._w = 0.0;
  42501. this._minimum = BABYLON.Tmp.Vector3[0];
  42502. this._maximum = BABYLON.Tmp.Vector3[1];
  42503. this.name = name;
  42504. this._scene = scene;
  42505. this._camera = scene.activeCamera;
  42506. this._pickable = options ? options.isPickable : false;
  42507. if (options && options.updatable) {
  42508. this._updatable = options.updatable;
  42509. }
  42510. else {
  42511. this._updatable = true;
  42512. }
  42513. if (this._pickable) {
  42514. this.pickedParticles = [];
  42515. }
  42516. }
  42517. /**
  42518. * Builds the SPS underlying mesh. Returns a standard Mesh.
  42519. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  42520. */
  42521. SolidParticleSystem.prototype.buildMesh = function () {
  42522. if (this.nbParticles === 0) {
  42523. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  42524. this.addShape(triangle, 1);
  42525. triangle.dispose();
  42526. }
  42527. this._positions32 = new Float32Array(this._positions);
  42528. this._uvs32 = new Float32Array(this._uvs);
  42529. this._colors32 = new Float32Array(this._colors);
  42530. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  42531. this._normals32 = new Float32Array(this._normals);
  42532. this._fixedNormal32 = new Float32Array(this._normals);
  42533. var vertexData = new BABYLON.VertexData();
  42534. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  42535. vertexData.indices = this._indices;
  42536. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  42537. if (this._uvs32) {
  42538. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  42539. ;
  42540. }
  42541. if (this._colors32) {
  42542. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  42543. }
  42544. var mesh = new BABYLON.Mesh(this.name, this._scene);
  42545. vertexData.applyToMesh(mesh, this._updatable);
  42546. this.mesh = mesh;
  42547. this.mesh.isPickable = this._pickable;
  42548. // free memory
  42549. this._positions = null;
  42550. this._normals = null;
  42551. this._uvs = null;
  42552. this._colors = null;
  42553. if (!this._updatable) {
  42554. this.particles.length = 0;
  42555. }
  42556. return mesh;
  42557. };
  42558. /**
  42559. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  42560. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  42561. * Thus the particles generated from `digest()` have their property `position` set yet.
  42562. * `mesh` (`Mesh`) is the mesh to be digested
  42563. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  42564. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  42565. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  42566. */
  42567. SolidParticleSystem.prototype.digest = function (mesh, options) {
  42568. var size = (options && options.facetNb) || 1;
  42569. var number = (options && options.number);
  42570. var delta = (options && options.delta) || 0;
  42571. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42572. var meshInd = mesh.getIndices();
  42573. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42574. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42575. var f = 0; // facet counter
  42576. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  42577. // compute size from number
  42578. if (number) {
  42579. number = (number > totalFacets) ? totalFacets : number;
  42580. size = Math.round(totalFacets / number);
  42581. delta = 0;
  42582. }
  42583. else {
  42584. size = (size > totalFacets) ? totalFacets : size;
  42585. }
  42586. var facetPos = []; // submesh positions
  42587. var facetInd = []; // submesh indices
  42588. var facetUV = []; // submesh UV
  42589. var facetCol = []; // submesh colors
  42590. var barycenter = BABYLON.Tmp.Vector3[0];
  42591. var rand;
  42592. var sizeO = size;
  42593. while (f < totalFacets) {
  42594. size = sizeO + Math.floor((1 + delta) * Math.random());
  42595. if (f > totalFacets - size) {
  42596. size = totalFacets - f;
  42597. }
  42598. // reset temp arrays
  42599. facetPos.length = 0;
  42600. facetInd.length = 0;
  42601. facetUV.length = 0;
  42602. facetCol.length = 0;
  42603. // iterate over "size" facets
  42604. var fi = 0;
  42605. for (var j = f * 3; j < (f + size) * 3; j++) {
  42606. facetInd.push(fi);
  42607. var i = meshInd[j];
  42608. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  42609. if (meshUV) {
  42610. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  42611. }
  42612. if (meshCol) {
  42613. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  42614. }
  42615. fi++;
  42616. }
  42617. // create a model shape for each single particle
  42618. var idx = this.nbParticles;
  42619. var shape = this._posToShape(facetPos);
  42620. var shapeUV = this._uvsToShapeUV(facetUV);
  42621. // compute the barycenter of the shape
  42622. var v;
  42623. for (v = 0; v < shape.length; v++) {
  42624. barycenter.addInPlace(shape[v]);
  42625. }
  42626. barycenter.scaleInPlace(1 / shape.length);
  42627. // shift the shape from its barycenter to the origin
  42628. for (v = 0; v < shape.length; v++) {
  42629. shape[v].subtractInPlace(barycenter);
  42630. }
  42631. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  42632. // add the particle in the SPS
  42633. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  42634. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  42635. // initialize the particle position
  42636. this.particles[this.nbParticles].position.addInPlace(barycenter);
  42637. this._index += shape.length;
  42638. idx++;
  42639. this.nbParticles++;
  42640. this._shapeCounter++;
  42641. f += size;
  42642. }
  42643. return this;
  42644. };
  42645. //reset copy
  42646. SolidParticleSystem.prototype._resetCopy = function () {
  42647. this._copy.position.x = 0;
  42648. this._copy.position.y = 0;
  42649. this._copy.position.z = 0;
  42650. this._copy.rotation.x = 0;
  42651. this._copy.rotation.y = 0;
  42652. this._copy.rotation.z = 0;
  42653. this._copy.rotationQuaternion = null;
  42654. this._copy.scaling.x = 1;
  42655. this._copy.scaling.y = 1;
  42656. this._copy.scaling.z = 1;
  42657. this._copy.uvs.x = 0;
  42658. this._copy.uvs.y = 0;
  42659. this._copy.uvs.z = 1;
  42660. this._copy.uvs.w = 1;
  42661. this._copy.color = null;
  42662. };
  42663. // _meshBuilder : inserts the shape model in the global SPS mesh
  42664. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  42665. var i;
  42666. var u = 0;
  42667. var c = 0;
  42668. this._resetCopy();
  42669. if (options && options.positionFunction) {
  42670. options.positionFunction(this._copy, idx, idxInShape);
  42671. }
  42672. if (this._copy.rotationQuaternion) {
  42673. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42674. }
  42675. else {
  42676. this._yaw = this._copy.rotation.y;
  42677. this._pitch = this._copy.rotation.x;
  42678. this._roll = this._copy.rotation.z;
  42679. this._quaternionRotationYPR();
  42680. }
  42681. this._quaternionToRotationMatrix();
  42682. for (i = 0; i < shape.length; i++) {
  42683. this._vertex.x = shape[i].x;
  42684. this._vertex.y = shape[i].y;
  42685. this._vertex.z = shape[i].z;
  42686. if (options && options.vertexFunction) {
  42687. options.vertexFunction(this._copy, this._vertex, i);
  42688. }
  42689. this._vertex.x *= this._copy.scaling.x;
  42690. this._vertex.y *= this._copy.scaling.y;
  42691. this._vertex.z *= this._copy.scaling.z;
  42692. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42693. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  42694. if (meshUV) {
  42695. 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);
  42696. u += 2;
  42697. }
  42698. if (this._copy.color) {
  42699. this._color = this._copy.color;
  42700. }
  42701. else if (meshCol && meshCol[c]) {
  42702. this._color.r = meshCol[c];
  42703. this._color.g = meshCol[c + 1];
  42704. this._color.b = meshCol[c + 2];
  42705. this._color.a = meshCol[c + 3];
  42706. }
  42707. else {
  42708. this._color.r = 1;
  42709. this._color.g = 1;
  42710. this._color.b = 1;
  42711. this._color.a = 1;
  42712. }
  42713. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  42714. c += 4;
  42715. }
  42716. for (i = 0; i < meshInd.length; i++) {
  42717. indices.push(p + meshInd[i]);
  42718. }
  42719. if (this._pickable) {
  42720. var nbfaces = meshInd.length / 3;
  42721. for (i = 0; i < nbfaces; i++) {
  42722. this.pickedParticles.push({ idx: idx, faceId: i });
  42723. }
  42724. }
  42725. };
  42726. // returns a shape array from positions array
  42727. SolidParticleSystem.prototype._posToShape = function (positions) {
  42728. var shape = [];
  42729. for (var i = 0; i < positions.length; i += 3) {
  42730. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  42731. }
  42732. return shape;
  42733. };
  42734. // returns a shapeUV array from a Vector4 uvs
  42735. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  42736. var shapeUV = [];
  42737. if (uvs) {
  42738. for (var i = 0; i < uvs.length; i++)
  42739. shapeUV.push(uvs[i]);
  42740. }
  42741. return shapeUV;
  42742. };
  42743. // adds a new particle object in the particles array
  42744. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  42745. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  42746. };
  42747. /**
  42748. * Adds some particles to the SPS from the model shape. Returns the shape id.
  42749. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  42750. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  42751. * `nb` (positive integer) the number of particles to be created from this model
  42752. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  42753. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  42754. */
  42755. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  42756. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42757. var meshInd = mesh.getIndices();
  42758. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42759. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42760. var shape = this._posToShape(meshPos);
  42761. var shapeUV = this._uvsToShapeUV(meshUV);
  42762. var posfunc = options ? options.positionFunction : null;
  42763. var vtxfunc = options ? options.vertexFunction : null;
  42764. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  42765. // particles
  42766. var idx = this.nbParticles;
  42767. for (var i = 0; i < nb; i++) {
  42768. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  42769. if (this._updatable) {
  42770. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  42771. }
  42772. this._index += shape.length;
  42773. idx++;
  42774. }
  42775. this.nbParticles += nb;
  42776. this._shapeCounter++;
  42777. return this._shapeCounter - 1;
  42778. };
  42779. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  42780. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  42781. this._resetCopy();
  42782. if (particle._model._positionFunction) {
  42783. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  42784. }
  42785. if (this._copy.rotationQuaternion) {
  42786. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  42787. }
  42788. else {
  42789. this._yaw = this._copy.rotation.y;
  42790. this._pitch = this._copy.rotation.x;
  42791. this._roll = this._copy.rotation.z;
  42792. this._quaternionRotationYPR();
  42793. }
  42794. this._quaternionToRotationMatrix();
  42795. this._shape = particle._model._shape;
  42796. for (var pt = 0; pt < this._shape.length; pt++) {
  42797. this._vertex.x = this._shape[pt].x;
  42798. this._vertex.y = this._shape[pt].y;
  42799. this._vertex.z = this._shape[pt].z;
  42800. if (particle._model._vertexFunction) {
  42801. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  42802. }
  42803. this._vertex.x *= this._copy.scaling.x;
  42804. this._vertex.y *= this._copy.scaling.y;
  42805. this._vertex.z *= this._copy.scaling.z;
  42806. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  42807. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  42808. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  42809. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  42810. }
  42811. particle.position.x = 0;
  42812. particle.position.y = 0;
  42813. particle.position.z = 0;
  42814. particle.rotation.x = 0;
  42815. particle.rotation.y = 0;
  42816. particle.rotation.z = 0;
  42817. particle.rotationQuaternion = null;
  42818. particle.scaling.x = 1;
  42819. particle.scaling.y = 1;
  42820. particle.scaling.z = 1;
  42821. };
  42822. /**
  42823. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  42824. */
  42825. SolidParticleSystem.prototype.rebuildMesh = function () {
  42826. for (var p = 0; p < this.particles.length; p++) {
  42827. this._rebuildParticle(this.particles[p]);
  42828. }
  42829. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42830. };
  42831. /**
  42832. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  42833. * This method calls `updateParticle()` for each particle of the SPS.
  42834. * For an animated SPS, it is usually called within the render loop.
  42835. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  42836. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  42837. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  42838. */
  42839. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  42840. if (start === void 0) { start = 0; }
  42841. if (end === void 0) { end = this.nbParticles - 1; }
  42842. if (update === void 0) { update = true; }
  42843. if (!this._updatable) {
  42844. return;
  42845. }
  42846. // custom beforeUpdate
  42847. this.beforeUpdateParticles(start, end, update);
  42848. this._cam_axisX.x = 1;
  42849. this._cam_axisX.y = 0;
  42850. this._cam_axisX.z = 0;
  42851. this._cam_axisY.x = 0;
  42852. this._cam_axisY.y = 1;
  42853. this._cam_axisY.z = 0;
  42854. this._cam_axisZ.x = 0;
  42855. this._cam_axisZ.y = 0;
  42856. this._cam_axisZ.z = 1;
  42857. // if the particles will always face the camera
  42858. if (this.billboard) {
  42859. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  42860. this._yaw = this.mesh.rotation.y;
  42861. this._pitch = this.mesh.rotation.x;
  42862. this._roll = this.mesh.rotation.z;
  42863. this._quaternionRotationYPR();
  42864. this._quaternionToRotationMatrix();
  42865. this._rotMatrix.invertToRef(this._invertMatrix);
  42866. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  42867. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  42868. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  42869. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  42870. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  42871. this._cam_axisY.normalize();
  42872. this._cam_axisX.normalize();
  42873. this._cam_axisZ.normalize();
  42874. }
  42875. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  42876. var idx = 0;
  42877. var index = 0;
  42878. var colidx = 0;
  42879. var colorIndex = 0;
  42880. var uvidx = 0;
  42881. var uvIndex = 0;
  42882. if (this._computeBoundingBox) {
  42883. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  42884. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  42885. }
  42886. // particle loop
  42887. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  42888. for (var p = start; p <= end; p++) {
  42889. this._particle = this.particles[p];
  42890. this._shape = this._particle._model._shape;
  42891. this._shapeUV = this._particle._model._shapeUV;
  42892. // call to custom user function to update the particle properties
  42893. this.updateParticle(this._particle);
  42894. // particle rotation matrix
  42895. if (this.billboard) {
  42896. this._particle.rotation.x = 0.0;
  42897. this._particle.rotation.y = 0.0;
  42898. }
  42899. if (this._computeParticleRotation) {
  42900. if (this._particle.rotationQuaternion) {
  42901. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  42902. }
  42903. else {
  42904. this._yaw = this._particle.rotation.y;
  42905. this._pitch = this._particle.rotation.x;
  42906. this._roll = this._particle.rotation.z;
  42907. this._quaternionRotationYPR();
  42908. }
  42909. this._quaternionToRotationMatrix();
  42910. }
  42911. for (var pt = 0; pt < this._shape.length; pt++) {
  42912. idx = index + pt * 3;
  42913. colidx = colorIndex + pt * 4;
  42914. uvidx = uvIndex + pt * 2;
  42915. this._vertex.x = this._shape[pt].x;
  42916. this._vertex.y = this._shape[pt].y;
  42917. this._vertex.z = this._shape[pt].z;
  42918. if (this._computeParticleVertex) {
  42919. this.updateParticleVertex(this._particle, this._vertex, pt);
  42920. }
  42921. // positions
  42922. this._vertex.x *= this._particle.scaling.x;
  42923. this._vertex.y *= this._particle.scaling.y;
  42924. this._vertex.z *= this._particle.scaling.z;
  42925. 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];
  42926. 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;
  42927. 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;
  42928. 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;
  42929. 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;
  42930. 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;
  42931. 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;
  42932. if (this._computeBoundingBox) {
  42933. if (this._positions32[idx] < this._minimum.x) {
  42934. this._minimum.x = this._positions32[idx];
  42935. }
  42936. if (this._positions32[idx] > this._maximum.x) {
  42937. this._maximum.x = this._positions32[idx];
  42938. }
  42939. if (this._positions32[idx + 1] < this._minimum.y) {
  42940. this._minimum.y = this._positions32[idx + 1];
  42941. }
  42942. if (this._positions32[idx + 1] > this._maximum.y) {
  42943. this._maximum.y = this._positions32[idx + 1];
  42944. }
  42945. if (this._positions32[idx + 2] < this._minimum.z) {
  42946. this._minimum.z = this._positions32[idx + 2];
  42947. }
  42948. if (this._positions32[idx + 2] > this._maximum.z) {
  42949. this._maximum.z = this._positions32[idx + 2];
  42950. }
  42951. }
  42952. // normals : if the particles can't be morphed then just rotate the normals
  42953. if (!this._computeParticleVertex && !this.billboard) {
  42954. this._normal.x = this._fixedNormal32[idx];
  42955. this._normal.y = this._fixedNormal32[idx + 1];
  42956. this._normal.z = this._fixedNormal32[idx + 2];
  42957. 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];
  42958. 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;
  42959. 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;
  42960. 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;
  42961. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42962. 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;
  42963. 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;
  42964. }
  42965. if (this._computeParticleColor) {
  42966. this._colors32[colidx] = this._particle.color.r;
  42967. this._colors32[colidx + 1] = this._particle.color.g;
  42968. this._colors32[colidx + 2] = this._particle.color.b;
  42969. this._colors32[colidx + 3] = this._particle.color.a;
  42970. }
  42971. if (this._computeParticleTexture) {
  42972. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42973. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42974. }
  42975. }
  42976. index = idx + 3;
  42977. colorIndex = colidx + 4;
  42978. uvIndex = uvidx + 2;
  42979. }
  42980. if (update) {
  42981. if (this._computeParticleColor) {
  42982. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42983. }
  42984. if (this._computeParticleTexture) {
  42985. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42986. }
  42987. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42988. if (!this.mesh.areNormalsFrozen) {
  42989. if (this._computeParticleVertex || this.billboard) {
  42990. // recompute the normals only if the particles can be morphed, update then the normal reference array
  42991. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  42992. for (var i = 0; i < this._normals32.length; i++) {
  42993. this._fixedNormal32[i] = this._normals32[i];
  42994. }
  42995. }
  42996. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42997. }
  42998. }
  42999. if (this._computeBoundingBox) {
  43000. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  43001. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  43002. }
  43003. this.afterUpdateParticles(start, end, update);
  43004. };
  43005. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  43006. this._halfroll = this._roll * 0.5;
  43007. this._halfpitch = this._pitch * 0.5;
  43008. this._halfyaw = this._yaw * 0.5;
  43009. this._sinRoll = Math.sin(this._halfroll);
  43010. this._cosRoll = Math.cos(this._halfroll);
  43011. this._sinPitch = Math.sin(this._halfpitch);
  43012. this._cosPitch = Math.cos(this._halfpitch);
  43013. this._sinYaw = Math.sin(this._halfyaw);
  43014. this._cosYaw = Math.cos(this._halfyaw);
  43015. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  43016. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  43017. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  43018. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  43019. };
  43020. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  43021. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  43022. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  43023. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  43024. this._rotMatrix.m[3] = 0;
  43025. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  43026. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  43027. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  43028. this._rotMatrix.m[7] = 0;
  43029. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  43030. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  43031. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  43032. this._rotMatrix.m[11] = 0;
  43033. this._rotMatrix.m[12] = 0;
  43034. this._rotMatrix.m[13] = 0;
  43035. this._rotMatrix.m[14] = 0;
  43036. this._rotMatrix.m[15] = 1.0;
  43037. };
  43038. /**
  43039. * Disposes the SPS
  43040. */
  43041. SolidParticleSystem.prototype.dispose = function () {
  43042. this.mesh.dispose();
  43043. this.vars = null;
  43044. // drop references to internal big arrays for the GC
  43045. this._positions = null;
  43046. this._indices = null;
  43047. this._normals = null;
  43048. this._uvs = null;
  43049. this._colors = null;
  43050. this._positions32 = null;
  43051. this._normals32 = null;
  43052. this._fixedNormal32 = null;
  43053. this._uvs32 = null;
  43054. this._colors32 = null;
  43055. this.pickedParticles = null;
  43056. };
  43057. /**
  43058. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  43059. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  43060. */
  43061. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  43062. if (!this._isVisibilityBoxLocked) {
  43063. this.mesh.refreshBoundingInfo();
  43064. }
  43065. };
  43066. /**
  43067. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  43068. * @param size the size (float) of the visibility box
  43069. * note : this doesn't lock the SPS mesh bounding box.
  43070. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  43071. */
  43072. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  43073. var vis = size / 2;
  43074. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  43075. };
  43076. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  43077. // getter and setter
  43078. get: function () {
  43079. return this._alwaysVisible;
  43080. },
  43081. /**
  43082. * Sets the SPS as always visible or not
  43083. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  43084. */
  43085. set: function (val) {
  43086. this._alwaysVisible = val;
  43087. this.mesh.alwaysSelectAsActiveMesh = val;
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  43093. get: function () {
  43094. return this._isVisibilityBoxLocked;
  43095. },
  43096. /**
  43097. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  43098. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  43099. */
  43100. set: function (val) {
  43101. this._isVisibilityBoxLocked = val;
  43102. this.mesh.getBoundingInfo().isLocked = val;
  43103. },
  43104. enumerable: true,
  43105. configurable: true
  43106. });
  43107. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  43108. // getters
  43109. get: function () {
  43110. return this._computeParticleRotation;
  43111. },
  43112. // Optimizer setters
  43113. /**
  43114. * Tells to `setParticles()` to compute the particle rotations or not.
  43115. * Default value : true. The SPS is faster when it's set to false.
  43116. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  43117. */
  43118. set: function (val) {
  43119. this._computeParticleRotation = val;
  43120. },
  43121. enumerable: true,
  43122. configurable: true
  43123. });
  43124. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  43125. get: function () {
  43126. return this._computeParticleColor;
  43127. },
  43128. /**
  43129. * Tells to `setParticles()` to compute the particle colors or not.
  43130. * Default value : true. The SPS is faster when it's set to false.
  43131. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  43132. */
  43133. set: function (val) {
  43134. this._computeParticleColor = val;
  43135. },
  43136. enumerable: true,
  43137. configurable: true
  43138. });
  43139. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  43140. get: function () {
  43141. return this._computeParticleTexture;
  43142. },
  43143. /**
  43144. * Tells to `setParticles()` to compute the particle textures or not.
  43145. * Default value : true. The SPS is faster when it's set to false.
  43146. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  43147. */
  43148. set: function (val) {
  43149. this._computeParticleTexture = val;
  43150. },
  43151. enumerable: true,
  43152. configurable: true
  43153. });
  43154. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  43155. get: function () {
  43156. return this._computeParticleVertex;
  43157. },
  43158. /**
  43159. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  43160. * Default value : false. The SPS is faster when it's set to false.
  43161. * Note : the particle custom vertex positions aren't stored values.
  43162. */
  43163. set: function (val) {
  43164. this._computeParticleVertex = val;
  43165. },
  43166. enumerable: true,
  43167. configurable: true
  43168. });
  43169. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  43170. get: function () {
  43171. return this._computeBoundingBox;
  43172. },
  43173. /**
  43174. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  43175. */
  43176. set: function (val) {
  43177. this._computeBoundingBox = val;
  43178. },
  43179. enumerable: true,
  43180. configurable: true
  43181. });
  43182. // =======================================================================
  43183. // Particle behavior logic
  43184. // these following methods may be overwritten by the user to fit his needs
  43185. /**
  43186. * This function does nothing. It may be overwritten to set all the particle first values.
  43187. * The SPS doesn't call this function, you may have to call it by your own.
  43188. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  43189. */
  43190. SolidParticleSystem.prototype.initParticles = function () {
  43191. };
  43192. /**
  43193. * This function does nothing. It may be overwritten to recycle a particle.
  43194. * The SPS doesn't call this function, you may have to call it by your own.
  43195. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  43196. */
  43197. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  43198. return particle;
  43199. };
  43200. /**
  43201. * Updates a particle : this function should be overwritten by the user.
  43202. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  43203. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  43204. * ex : just set a particle position or velocity and recycle conditions
  43205. */
  43206. SolidParticleSystem.prototype.updateParticle = function (particle) {
  43207. return particle;
  43208. };
  43209. /**
  43210. * Updates a vertex of a particle : it can be overwritten by the user.
  43211. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  43212. * @param particle the current particle
  43213. * @param vertex the current index of the current particle
  43214. * @param pt the index of the current vertex in the particle shape
  43215. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  43216. * ex : just set a vertex particle position
  43217. */
  43218. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  43219. return vertex;
  43220. };
  43221. /**
  43222. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  43223. * This does nothing and may be overwritten by the user.
  43224. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  43225. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  43226. * @param update the boolean update value actually passed to setParticles()
  43227. */
  43228. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  43229. };
  43230. /**
  43231. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  43232. * This will be passed three parameters.
  43233. * This does nothing and may be overwritten by the user.
  43234. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  43235. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  43236. * @param update the boolean update value actually passed to setParticles()
  43237. */
  43238. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  43239. };
  43240. return SolidParticleSystem;
  43241. })();
  43242. BABYLON.SolidParticleSystem = SolidParticleSystem;
  43243. })(BABYLON || (BABYLON = {}));
  43244. var BABYLON;
  43245. (function (BABYLON) {
  43246. var Internals;
  43247. (function (Internals) {
  43248. var FileFaceOrientation = (function () {
  43249. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43250. this.name = name;
  43251. this.worldAxisForNormal = worldAxisForNormal;
  43252. this.worldAxisForFileX = worldAxisForFileX;
  43253. this.worldAxisForFileY = worldAxisForFileY;
  43254. }
  43255. return FileFaceOrientation;
  43256. })();
  43257. ;
  43258. /**
  43259. * Helper class dealing with the extraction of spherical polynomial dataArray
  43260. * from a cube map.
  43261. */
  43262. var CubeMapToSphericalPolynomialTools = (function () {
  43263. function CubeMapToSphericalPolynomialTools() {
  43264. }
  43265. /**
  43266. * Converts a cubemap to the according Spherical Polynomial data.
  43267. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43268. *
  43269. * @param cubeInfo The Cube map to extract the information from.
  43270. * @return The Spherical Polynomial data.
  43271. */
  43272. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43273. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43274. var totalSolidAngle = 0.0;
  43275. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43276. var du = 2.0 / cubeInfo.size;
  43277. var dv = du;
  43278. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43279. var minUV = du * 0.5 - 1.0;
  43280. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43281. var fileFace = this.FileFaces[faceIndex];
  43282. var dataArray = cubeInfo[fileFace.name];
  43283. var v = minUV;
  43284. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43285. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43286. // Because SP is still linear, so summation is fine in that basis.
  43287. for (var y = 0; y < cubeInfo.size; y++) {
  43288. var u = minUV;
  43289. for (var x = 0; x < cubeInfo.size; x++) {
  43290. // World direction (not normalised)
  43291. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43292. worldDirection.normalize();
  43293. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43294. if (1) {
  43295. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  43296. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  43297. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  43298. var color = new BABYLON.Color3(r, g, b);
  43299. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43300. }
  43301. else {
  43302. if (faceIndex == 0) {
  43303. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  43304. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  43305. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  43306. }
  43307. else if (faceIndex == 1) {
  43308. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  43309. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  43310. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  43311. }
  43312. else if (faceIndex == 2) {
  43313. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  43314. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  43315. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  43316. }
  43317. else if (faceIndex == 3) {
  43318. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  43319. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  43320. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  43321. }
  43322. else if (faceIndex == 4) {
  43323. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  43324. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  43325. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  43326. }
  43327. else if (faceIndex == 5) {
  43328. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  43329. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  43330. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  43331. }
  43332. 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]);
  43333. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43334. }
  43335. totalSolidAngle += deltaSolidAngle;
  43336. u += du;
  43337. }
  43338. v += dv;
  43339. }
  43340. }
  43341. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  43342. var correction = correctSolidAngle / totalSolidAngle;
  43343. sphericalHarmonics.scale(correction);
  43344. // Additionally scale by pi -- audit needed
  43345. sphericalHarmonics.scale(1.0 / Math.PI);
  43346. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  43347. };
  43348. CubeMapToSphericalPolynomialTools.FileFaces = [
  43349. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43350. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43351. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43352. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43353. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43354. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43355. ];
  43356. return CubeMapToSphericalPolynomialTools;
  43357. })();
  43358. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43359. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43360. })(BABYLON || (BABYLON = {}));
  43361. var BABYLON;
  43362. (function (BABYLON) {
  43363. var Internals;
  43364. (function (Internals) {
  43365. /**
  43366. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  43367. */
  43368. var PanoramaToCubeMapTools = (function () {
  43369. function PanoramaToCubeMapTools() {
  43370. }
  43371. /**
  43372. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  43373. *
  43374. * @param float32Array The source data.
  43375. * @param inputWidth The width of the input panorama.
  43376. * @param inputhHeight The height of the input panorama.
  43377. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  43378. * @return The cubemap data
  43379. */
  43380. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  43381. if (!float32Array) {
  43382. throw "ConvertPanoramaToCubemap: input cannot be null";
  43383. }
  43384. if (float32Array.length != inputWidth * inputHeight * 3) {
  43385. throw "ConvertPanoramaToCubemap: input size is wrong";
  43386. }
  43387. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  43388. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  43389. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  43390. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  43391. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  43392. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  43393. return {
  43394. front: textureFront,
  43395. back: textureBack,
  43396. left: textureLeft,
  43397. right: textureRight,
  43398. up: textureUp,
  43399. down: textureDown,
  43400. size: size
  43401. };
  43402. };
  43403. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  43404. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  43405. var textureArray = new Float32Array(buffer);
  43406. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  43407. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  43408. var dy = 1 / texSize;
  43409. var fy = 0;
  43410. for (var y = 0; y < texSize; y++) {
  43411. var xv1 = faceData[0];
  43412. var xv2 = faceData[2];
  43413. for (var x = 0; x < texSize; x++) {
  43414. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  43415. v.normalize();
  43416. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  43417. // 3 channels per pixels
  43418. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  43419. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  43420. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  43421. xv1 = xv1.add(rotDX1);
  43422. xv2 = xv2.add(rotDX2);
  43423. }
  43424. fy += dy;
  43425. }
  43426. return textureArray;
  43427. };
  43428. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  43429. var theta = Math.atan2(vDir.z, vDir.x);
  43430. var phi = Math.acos(vDir.y);
  43431. while (theta < -Math.PI)
  43432. theta += 2 * Math.PI;
  43433. while (theta > Math.PI)
  43434. theta -= 2 * Math.PI;
  43435. var dx = theta / Math.PI;
  43436. var dy = phi / Math.PI;
  43437. // recenter.
  43438. dx = dx * 0.5 + 0.5;
  43439. var px = Math.round(dx * inputWidth);
  43440. if (px < 0)
  43441. px = 0;
  43442. else if (px >= inputWidth)
  43443. px = inputWidth - 1;
  43444. var py = Math.round(dy * inputHeight);
  43445. if (py < 0)
  43446. py = 0;
  43447. else if (py >= inputHeight)
  43448. py = inputHeight - 1;
  43449. var inputY = (inputHeight - py - 1);
  43450. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  43451. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  43452. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  43453. return {
  43454. r: r,
  43455. g: g,
  43456. b: b
  43457. };
  43458. };
  43459. PanoramaToCubeMapTools.FACE_FRONT = [
  43460. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  43461. new BABYLON.Vector3(1.0, -1.0, -1.0),
  43462. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  43463. new BABYLON.Vector3(1.0, 1.0, -1.0)
  43464. ];
  43465. PanoramaToCubeMapTools.FACE_BACK = [
  43466. new BABYLON.Vector3(1.0, -1.0, 1.0),
  43467. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  43468. new BABYLON.Vector3(1.0, 1.0, 1.0),
  43469. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  43470. ];
  43471. PanoramaToCubeMapTools.FACE_RIGHT = [
  43472. new BABYLON.Vector3(1.0, -1.0, -1.0),
  43473. new BABYLON.Vector3(1.0, -1.0, 1.0),
  43474. new BABYLON.Vector3(1.0, 1.0, -1.0),
  43475. new BABYLON.Vector3(1.0, 1.0, 1.0)
  43476. ];
  43477. PanoramaToCubeMapTools.FACE_LEFT = [
  43478. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  43479. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  43480. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  43481. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  43482. ];
  43483. PanoramaToCubeMapTools.FACE_DOWN = [
  43484. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  43485. new BABYLON.Vector3(1.0, 1.0, -1.0),
  43486. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  43487. new BABYLON.Vector3(1.0, 1.0, 1.0)
  43488. ];
  43489. PanoramaToCubeMapTools.FACE_UP = [
  43490. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  43491. new BABYLON.Vector3(1.0, -1.0, 1.0),
  43492. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  43493. new BABYLON.Vector3(1.0, -1.0, -1.0)
  43494. ];
  43495. return PanoramaToCubeMapTools;
  43496. })();
  43497. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  43498. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43499. })(BABYLON || (BABYLON = {}));
  43500. var BABYLON;
  43501. (function (BABYLON) {
  43502. var Internals;
  43503. (function (Internals) {
  43504. ;
  43505. /**
  43506. * This groups tools to convert HDR texture to native colors array.
  43507. */
  43508. var HDRTools = (function () {
  43509. function HDRTools() {
  43510. }
  43511. HDRTools.Ldexp = function (mantissa, exponent) {
  43512. if (exponent > 1023) {
  43513. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  43514. }
  43515. if (exponent < -1074) {
  43516. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  43517. }
  43518. return mantissa * Math.pow(2, exponent);
  43519. };
  43520. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  43521. if (exponent > 0) {
  43522. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  43523. float32array[index + 0] = red * exponent;
  43524. float32array[index + 1] = green * exponent;
  43525. float32array[index + 2] = blue * exponent;
  43526. }
  43527. else {
  43528. float32array[index + 0] = 0;
  43529. float32array[index + 1] = 0;
  43530. float32array[index + 2] = 0;
  43531. }
  43532. };
  43533. HDRTools.readStringLine = function (uint8array, startIndex) {
  43534. var line = "";
  43535. var character = "";
  43536. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  43537. character = String.fromCharCode(uint8array[i]);
  43538. if (character == "\n") {
  43539. break;
  43540. }
  43541. line += character;
  43542. }
  43543. return line;
  43544. };
  43545. /**
  43546. * Reads header information from an RGBE texture stored in a native array.
  43547. * More information on this format are available here:
  43548. * https://en.wikipedia.org/wiki/RGBE_image_format
  43549. *
  43550. * @param uint8array The binary file stored in native array.
  43551. * @return The header information.
  43552. */
  43553. HDRTools.RGBE_ReadHeader = function (uint8array) {
  43554. var height = 0;
  43555. var width = 0;
  43556. var line = this.readStringLine(uint8array, 0);
  43557. if (line[0] != '#' || line[1] != '?') {
  43558. throw "Bad HDR Format.";
  43559. }
  43560. var endOfHeader = false;
  43561. var findFormat = false;
  43562. var lineIndex = 0;
  43563. do {
  43564. lineIndex += (line.length + 1);
  43565. line = this.readStringLine(uint8array, lineIndex);
  43566. if (line == "FORMAT=32-bit_rle_rgbe") {
  43567. findFormat = true;
  43568. }
  43569. else if (line.length == 0) {
  43570. endOfHeader = true;
  43571. }
  43572. } while (!endOfHeader);
  43573. if (!findFormat) {
  43574. throw "HDR Bad header format, unsupported FORMAT";
  43575. }
  43576. lineIndex += (line.length + 1);
  43577. line = this.readStringLine(uint8array, lineIndex);
  43578. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  43579. var match = sizeRegexp.exec(line);
  43580. // TODO. Support +Y and -X if needed.
  43581. if (match.length < 3) {
  43582. throw "HDR Bad header format, no size";
  43583. }
  43584. width = parseInt(match[2]);
  43585. height = parseInt(match[1]);
  43586. if (width < 8 || width > 0x7fff) {
  43587. throw "HDR Bad header format, unsupported size";
  43588. }
  43589. lineIndex += (line.length + 1);
  43590. return {
  43591. height: height,
  43592. width: width,
  43593. dataPosition: lineIndex
  43594. };
  43595. };
  43596. /**
  43597. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  43598. * This RGBE texture needs to store the information as a panorama.
  43599. *
  43600. * More information on this format are available here:
  43601. * https://en.wikipedia.org/wiki/RGBE_image_format
  43602. *
  43603. * @param buffer The binary file stored in an array buffer.
  43604. * @param size The expected size of the extracted cubemap.
  43605. * @return The Cube Map information.
  43606. */
  43607. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  43608. var uint8array = new Uint8Array(buffer);
  43609. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  43610. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  43611. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  43612. return cubeMapData;
  43613. };
  43614. /**
  43615. * Returns the pixels data extracted from an RGBE texture.
  43616. * This pixels will be stored left to right up to down in the R G B order in one array.
  43617. *
  43618. * More information on this format are available here:
  43619. * https://en.wikipedia.org/wiki/RGBE_image_format
  43620. *
  43621. * @param uint8array The binary file stored in an array buffer.
  43622. * @param hdrInfo The header information of the file.
  43623. * @return The pixels data in RGB right to left up to down order.
  43624. */
  43625. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  43626. // Keep for multi format supports.
  43627. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  43628. };
  43629. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  43630. var num_scanlines = hdrInfo.height;
  43631. var scanline_width = hdrInfo.width;
  43632. var a, b, c, d, count;
  43633. var dataIndex = hdrInfo.dataPosition;
  43634. var index = 0, endIndex = 0, i = 0;
  43635. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  43636. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  43637. // 3 channels of 4 bytes per pixel in float.
  43638. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  43639. var resultArray = new Float32Array(resultBuffer);
  43640. // read in each successive scanline
  43641. while (num_scanlines > 0) {
  43642. a = uint8array[dataIndex++];
  43643. b = uint8array[dataIndex++];
  43644. c = uint8array[dataIndex++];
  43645. d = uint8array[dataIndex++];
  43646. if (a != 2 || b != 2 || (c & 0x80)) {
  43647. // this file is not run length encoded
  43648. throw "HDR Bad header format, not RLE";
  43649. }
  43650. if (((c << 8) | d) != scanline_width) {
  43651. throw "HDR Bad header format, wrong scan line width";
  43652. }
  43653. index = 0;
  43654. // read each of the four channels for the scanline into the buffer
  43655. for (i = 0; i < 4; i++) {
  43656. endIndex = (i + 1) * scanline_width;
  43657. while (index < endIndex) {
  43658. a = uint8array[dataIndex++];
  43659. b = uint8array[dataIndex++];
  43660. if (a > 128) {
  43661. // a run of the same value
  43662. count = a - 128;
  43663. if ((count == 0) || (count > endIndex - index)) {
  43664. throw "HDR Bad Format, bad scanline data (run)";
  43665. }
  43666. while (count-- > 0) {
  43667. scanLineArray[index++] = b;
  43668. }
  43669. }
  43670. else {
  43671. // a non-run
  43672. count = a;
  43673. if ((count == 0) || (count > endIndex - index)) {
  43674. throw "HDR Bad Format, bad scanline data (non-run)";
  43675. }
  43676. scanLineArray[index++] = b;
  43677. if (--count > 0) {
  43678. for (var j = 0; j < count; j++) {
  43679. scanLineArray[index++] = uint8array[dataIndex++];
  43680. }
  43681. }
  43682. }
  43683. }
  43684. }
  43685. // now convert data from buffer into floats
  43686. for (i = 0; i < scanline_width; i++) {
  43687. a = scanLineArray[i];
  43688. b = scanLineArray[i + scanline_width];
  43689. c = scanLineArray[i + 2 * scanline_width];
  43690. d = scanLineArray[i + 3 * scanline_width];
  43691. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  43692. }
  43693. num_scanlines--;
  43694. }
  43695. return resultArray;
  43696. };
  43697. return HDRTools;
  43698. })();
  43699. Internals.HDRTools = HDRTools;
  43700. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43701. })(BABYLON || (BABYLON = {}));
  43702. //_______________________________________________________________
  43703. // Extracted from CubeMapGen:
  43704. // https://code.google.com/archive/p/cubemapgen/
  43705. //
  43706. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  43707. //_______________________________________________________________
  43708. var BABYLON;
  43709. (function (BABYLON) {
  43710. var Internals;
  43711. (function (Internals) {
  43712. /**
  43713. * The bounding box information used during the conversion process.
  43714. */
  43715. var CMGBoundinBox = (function () {
  43716. function CMGBoundinBox() {
  43717. this.min = new BABYLON.Vector3(0, 0, 0);
  43718. this.max = new BABYLON.Vector3(0, 0, 0);
  43719. this.clear();
  43720. }
  43721. CMGBoundinBox.prototype.clear = function () {
  43722. this.min.x = CMGBoundinBox.MAX;
  43723. this.min.y = CMGBoundinBox.MAX;
  43724. this.min.z = CMGBoundinBox.MAX;
  43725. this.max.x = CMGBoundinBox.MIN;
  43726. this.max.y = CMGBoundinBox.MIN;
  43727. this.max.z = CMGBoundinBox.MIN;
  43728. };
  43729. CMGBoundinBox.prototype.augment = function (x, y, z) {
  43730. this.min.x = Math.min(this.min.x, x);
  43731. this.min.y = Math.min(this.min.y, y);
  43732. this.min.z = Math.min(this.min.z, z);
  43733. this.max.x = Math.max(this.max.x, x);
  43734. this.max.y = Math.max(this.max.y, y);
  43735. this.max.z = Math.max(this.max.z, z);
  43736. };
  43737. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  43738. this.min.x = Math.max(this.min.x, x);
  43739. this.min.y = Math.max(this.min.y, y);
  43740. this.min.z = Math.max(this.min.z, z);
  43741. };
  43742. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  43743. this.max.x = Math.min(this.max.x, x);
  43744. this.max.y = Math.min(this.max.y, y);
  43745. this.max.z = Math.min(this.max.z, z);
  43746. };
  43747. CMGBoundinBox.prototype.empty = function () {
  43748. if ((this.min.x > this.max.y) ||
  43749. (this.min.y > this.max.y) ||
  43750. (this.min.z > this.max.y)) {
  43751. return true;
  43752. }
  43753. else {
  43754. return false;
  43755. }
  43756. };
  43757. CMGBoundinBox.MAX = Number.MAX_VALUE;
  43758. CMGBoundinBox.MIN = Number.MIN_VALUE;
  43759. return CMGBoundinBox;
  43760. })();
  43761. /**
  43762. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  43763. * required by the glossinees of a material.
  43764. *
  43765. * This only supports the cosine drop power as well as Warp fixup generation method.
  43766. *
  43767. * This is using the process from CubeMapGen described here:
  43768. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  43769. */
  43770. var PMREMGenerator = (function () {
  43771. /**
  43772. * Constructor of the generator.
  43773. *
  43774. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  43775. * @param inputSize The size of the cubemap faces
  43776. * @param outputSize The size of the output cubemap faces
  43777. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  43778. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  43779. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  43780. * @param specularPower The max specular level of the desired cubemap
  43781. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  43782. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  43783. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  43784. */
  43785. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  43786. this.input = input;
  43787. this.inputSize = inputSize;
  43788. this.outputSize = outputSize;
  43789. this.maxNumMipLevels = maxNumMipLevels;
  43790. this.numChannels = numChannels;
  43791. this.isFloat = isFloat;
  43792. this.specularPower = specularPower;
  43793. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  43794. this.excludeBase = excludeBase;
  43795. this.fixup = fixup;
  43796. this._outputSurface = [];
  43797. this._numMipLevels = 0;
  43798. }
  43799. /**
  43800. * Launches the filter process and return the result.
  43801. *
  43802. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  43803. */
  43804. PMREMGenerator.prototype.filterCubeMap = function () {
  43805. // Init cubemap processor
  43806. this.init();
  43807. // Filters the cubemap
  43808. this.filterCubeMapMipChain();
  43809. // Returns the filtered mips.
  43810. return this._outputSurface;
  43811. };
  43812. PMREMGenerator.prototype.init = function () {
  43813. var i;
  43814. var j;
  43815. var mipLevelSize;
  43816. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  43817. if (this.maxNumMipLevels == 0) {
  43818. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  43819. }
  43820. //first miplevel size
  43821. mipLevelSize = this.outputSize;
  43822. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  43823. for (j = 0; j < this.maxNumMipLevels; j++) {
  43824. this._outputSurface.length++;
  43825. this._outputSurface[j] = [];
  43826. //Iterate over faces for output images
  43827. for (i = 0; i < 6; i++) {
  43828. this._outputSurface[j].length++;
  43829. // Initializes a new array for the output.
  43830. if (this.isFloat) {
  43831. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  43832. }
  43833. else {
  43834. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  43835. }
  43836. }
  43837. //next mip level is half size
  43838. mipLevelSize >>= 1;
  43839. this._numMipLevels++;
  43840. //terminate if mip chain becomes too small
  43841. if (mipLevelSize == 0) {
  43842. this.maxNumMipLevels = j;
  43843. return;
  43844. }
  43845. }
  43846. };
  43847. //--------------------------------------------------------------------------------------
  43848. //Cube map filtering and mip chain generation.
  43849. // the cube map filtereing is specified using a number of parameters:
  43850. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  43851. // indicates the region of the hemisphere to filter over for each tap.
  43852. //
  43853. // Note that the top mip level is also a filtered version of the original input images
  43854. // as well in order to create mip chains for diffuse environment illumination.
  43855. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  43856. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  43857. //
  43858. // Then the mip angle used to genreate the next level of the mip chain from the first level
  43859. // is a_InitialMipAngle
  43860. //
  43861. // The angle for the subsequent levels of the mip chain are specified by their parents
  43862. // filtering angle and a per-level scale and bias
  43863. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  43864. //
  43865. //--------------------------------------------------------------------------------------
  43866. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  43867. // First, take count of the lighting model to modify SpecularPower
  43868. // 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;
  43869. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  43870. //Cone angle start (for generating subsequent mip levels)
  43871. var currentSpecularPower = this.specularPower;
  43872. //Build filter lookup tables based on the source miplevel size
  43873. this.precomputeFilterLookupTables(this.inputSize);
  43874. // Note that we need to filter the first level before generating mipmap
  43875. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  43876. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  43877. // TODO : Write a function to copy and scale the base mipmap in output
  43878. // I am just lazy here and just put a high specular power value, and do some if.
  43879. if (this.excludeBase && (levelIndex == 0)) {
  43880. // 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).
  43881. currentSpecularPower = 100000.0;
  43882. }
  43883. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  43884. var srcCubeImage = this.input;
  43885. var dstCubeImage = this._outputSurface[levelIndex];
  43886. var dstSize = this.outputSize >> levelIndex;
  43887. // Compute required angle.
  43888. var angle = this.getBaseFilterAngle(currentSpecularPower);
  43889. // filter cube surfaces
  43890. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  43891. // fix seams
  43892. if (this.fixup) {
  43893. this.fixupCubeEdges(dstCubeImage, dstSize);
  43894. }
  43895. // Decrease the specular power to generate the mipmap chain
  43896. // TODO : Use another method for Exclude (see first comment at start of the function
  43897. if (this.excludeBase && (levelIndex == 0)) {
  43898. currentSpecularPower = this.specularPower;
  43899. }
  43900. currentSpecularPower *= this.cosinePowerDropPerMip;
  43901. }
  43902. };
  43903. //--------------------------------------------------------------------------------------
  43904. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  43905. // It allow to optimize the texel to access base on the specular power.
  43906. //--------------------------------------------------------------------------------------
  43907. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  43908. // We want to find the alpha such that:
  43909. // cos(alpha)^cosinePower = epsilon
  43910. // That's: acos(epsilon^(1/cosinePower))
  43911. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  43912. var angle = 180.0;
  43913. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  43914. angle *= 180.0 / Math.PI; // Convert to degree
  43915. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  43916. return angle;
  43917. };
  43918. //--------------------------------------------------------------------------------------
  43919. //Builds the following lookup tables prior to filtering:
  43920. // -normalizer cube map
  43921. // -tap weight lookup table
  43922. //
  43923. //--------------------------------------------------------------------------------------
  43924. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  43925. var srcTexelAngle;
  43926. var iCubeFace;
  43927. //clear pre-existing normalizer cube map
  43928. this._normCubeMap = [];
  43929. //Normalized vectors per cubeface and per-texel solid angle
  43930. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  43931. };
  43932. //--------------------------------------------------------------------------------------
  43933. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  43934. //
  43935. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  43936. //
  43937. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  43938. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  43939. // below
  43940. //--------------------------------------------------------------------------------------
  43941. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  43942. var iCubeFace;
  43943. var u;
  43944. var v;
  43945. //iterate over cube faces
  43946. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43947. //First three channels for norm cube, and last channel for solid angle
  43948. this._normCubeMap.push(new Float32Array(size * size * 4));
  43949. //fast texture walk, build normalizer cube map
  43950. var facesData = this.input[iCubeFace];
  43951. for (v = 0; v < size; v++) {
  43952. for (u = 0; u < size; u++) {
  43953. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  43954. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  43955. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  43956. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  43957. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  43958. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  43959. }
  43960. }
  43961. }
  43962. };
  43963. //--------------------------------------------------------------------------------------
  43964. // Convert cubemap face texel coordinates and face idx to 3D vector
  43965. // note the U and V coords are integer coords and range from 0 to size-1
  43966. // this routine can be used to generate a normalizer cube map
  43967. //--------------------------------------------------------------------------------------
  43968. // SL BEGIN
  43969. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  43970. var nvcU;
  43971. var nvcV;
  43972. var tempVec;
  43973. // Change from original AMD code
  43974. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43975. // + 0.5f is for texel center addressing
  43976. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  43977. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  43978. // warp fixup
  43979. if (fixup && size > 1) {
  43980. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  43981. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  43982. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  43983. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  43984. }
  43985. // Get current vector
  43986. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  43987. // U contribution
  43988. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43989. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  43990. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  43991. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  43992. // V contribution and Sum
  43993. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43994. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  43995. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  43996. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  43997. //add face axis
  43998. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  43999. PMREMGenerator._vectorTemp.x += faceAxis[0];
  44000. PMREMGenerator._vectorTemp.y += faceAxis[1];
  44001. PMREMGenerator._vectorTemp.z += faceAxis[2];
  44002. //normalize vector
  44003. PMREMGenerator._vectorTemp.normalize();
  44004. return PMREMGenerator._vectorTemp;
  44005. };
  44006. //--------------------------------------------------------------------------------------
  44007. // Convert 3D vector to cubemap face texel coordinates and face idx
  44008. // note the U and V coords are integer coords and range from 0 to size-1
  44009. // this routine can be used to generate a normalizer cube map
  44010. //
  44011. // returns face IDX and texel coords
  44012. //--------------------------------------------------------------------------------------
  44013. // SL BEGIN
  44014. /*
  44015. Mapping Texture Coordinates to Cube Map Faces
  44016. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  44017. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  44018. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  44019. map arrangement in Pixar's RenderMan package.
  44020. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  44021. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  44022. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  44023. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  44024. the major axis direction). The target column in the table below explains how the major axis direction
  44025. maps to the 2D image of a particular cube map target.
  44026. major axis
  44027. direction target sc tc ma
  44028. ---------- --------------------------------- --- --- ---
  44029. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  44030. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  44031. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  44032. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  44033. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  44034. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  44035. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  44036. an updated (s,t) is calculated as follows
  44037. s = ( sc/|ma| + 1 ) / 2
  44038. t = ( tc/|ma| + 1 ) / 2
  44039. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  44040. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  44041. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  44042. */
  44043. // Note this method return U and V in range from 0 to size-1
  44044. // SL END
  44045. // Store the information in vector3 for convenience (faceindex, u, v)
  44046. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  44047. var maxCoord;
  44048. var faceIdx;
  44049. //absolute value 3
  44050. var absX = Math.abs(x);
  44051. var absY = Math.abs(y);
  44052. var absZ = Math.abs(z);
  44053. if (absX >= absY && absX >= absZ) {
  44054. maxCoord = absX;
  44055. if (x >= 0) {
  44056. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  44057. }
  44058. else {
  44059. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  44060. }
  44061. }
  44062. else if (absY >= absX && absY >= absZ) {
  44063. maxCoord = absY;
  44064. if (y >= 0) {
  44065. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  44066. }
  44067. else {
  44068. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  44069. }
  44070. }
  44071. else {
  44072. maxCoord = absZ;
  44073. if (z >= 0) {
  44074. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  44075. }
  44076. else {
  44077. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  44078. }
  44079. }
  44080. //divide through by max coord so face vector lies on cube face
  44081. var scale = 1 / maxCoord;
  44082. x *= scale;
  44083. y *= scale;
  44084. z *= scale;
  44085. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  44086. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  44087. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  44088. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  44089. // Modify original AMD code to return value from 0 to Size - 1
  44090. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  44091. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  44092. PMREMGenerator._vectorTemp.x = faceIdx;
  44093. PMREMGenerator._vectorTemp.y = u;
  44094. PMREMGenerator._vectorTemp.z = v;
  44095. return PMREMGenerator._vectorTemp;
  44096. };
  44097. //--------------------------------------------------------------------------------------
  44098. //Original code from Ignacio CastaÒo
  44099. // This formula is from Manne ÷hrstrˆm's thesis.
  44100. // Take two coordiantes in the range [-1, 1] that define a portion of a
  44101. // cube face and return the area of the projection of that portion on the
  44102. // surface of the sphere.
  44103. //--------------------------------------------------------------------------------------
  44104. PMREMGenerator.prototype.areaElement = function (x, y) {
  44105. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  44106. };
  44107. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  44108. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  44109. // (+ 0.5f is for texel center addressing)
  44110. u = (2.0 * (u + 0.5) / size) - 1.0;
  44111. v = (2.0 * (v + 0.5) / size) - 1.0;
  44112. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  44113. var invResolution = 1.0 / size;
  44114. // U and V are the -1..1 texture coordinate on the current face.
  44115. // Get projected area for this texel
  44116. var x0 = u - invResolution;
  44117. var y0 = v - invResolution;
  44118. var x1 = u + invResolution;
  44119. var y1 = v + invResolution;
  44120. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  44121. return solidAngle;
  44122. };
  44123. //--------------------------------------------------------------------------------------
  44124. //The key to the speed of these filtering routines is to quickly define a per-face
  44125. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  44126. // Later these pixels are selectively processed based on their dot products to see if
  44127. // they reside within the filtering cone.
  44128. //
  44129. //This is done by computing the smallest per-texel angle to get a conservative estimate
  44130. // of the number of texels needed to be covered in width and height order to filter the
  44131. // region. the bounding box for the center taps face is defined first, and if the
  44132. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  44133. // defined next
  44134. //--------------------------------------------------------------------------------------
  44135. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  44136. // note that pixels within these regions may be rejected
  44137. // based on the anlge
  44138. var iCubeFace;
  44139. var u;
  44140. var v;
  44141. // bounding box per face to specify region to process
  44142. var filterExtents = [];
  44143. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  44144. filterExtents.push(new CMGBoundinBox());
  44145. }
  44146. // min angle a src texel can cover (in degrees)
  44147. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  44148. // angle about center tap to define filter cone
  44149. // filter angle is 1/2 the cone angle
  44150. var filterAngle = filterConeAngle / 2.0;
  44151. //ensure filter angle is larger than a texel
  44152. if (filterAngle < srcTexelAngle) {
  44153. filterAngle = srcTexelAngle;
  44154. }
  44155. //ensure filter cone is always smaller than the hemisphere
  44156. if (filterAngle > 90.0) {
  44157. filterAngle = 90.0;
  44158. }
  44159. // the maximum number of texels in 1D the filter cone angle will cover
  44160. // used to determine bounding box size for filter extents
  44161. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  44162. // ensure conservative region always covers at least one texel
  44163. if (filterSize < 1) {
  44164. filterSize = 1;
  44165. }
  44166. // dotProdThresh threshold based on cone angle to determine whether or not taps
  44167. // reside within the cone angle
  44168. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  44169. // process required faces
  44170. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  44171. //iterate over dst cube map face texel
  44172. for (v = 0; v < dstSize; v++) {
  44173. for (u = 0; u < dstSize; u++) {
  44174. //get center tap direction
  44175. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  44176. //clear old per-face filter extents
  44177. this.clearFilterExtents(filterExtents);
  44178. //define per-face filter extents
  44179. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  44180. //perform filtering of src faces using filter extents
  44181. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  44182. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  44183. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  44184. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  44185. }
  44186. }
  44187. }
  44188. };
  44189. //--------------------------------------------------------------------------------------
  44190. //Clear filter extents for the 6 cube map faces
  44191. //--------------------------------------------------------------------------------------
  44192. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  44193. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  44194. filterExtents[iCubeFaces].clear();
  44195. }
  44196. };
  44197. //--------------------------------------------------------------------------------------
  44198. //Define per-face bounding box filter extents
  44199. //
  44200. // These define conservative texel regions in each of the faces the filter can possibly
  44201. // process. When the pixels in the regions are actually processed, the dot product
  44202. // between the tap vector and the center tap vector is used to determine the weight of
  44203. // the tap and whether or not the tap is within the cone.
  44204. //
  44205. //--------------------------------------------------------------------------------------
  44206. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  44207. //neighboring face and bleed over amount, and width of BBOX for
  44208. // left, right, top, and bottom edges of this face
  44209. var bleedOverAmount = [0, 0, 0, 0];
  44210. var bleedOverBBoxMin = [0, 0, 0, 0];
  44211. var bleedOverBBoxMax = [0, 0, 0, 0];
  44212. var neighborFace;
  44213. var neighborEdge;
  44214. var oppositeFaceIdx;
  44215. //get face idx, and u, v info from center tap dir
  44216. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  44217. var faceIdx = result.x;
  44218. var u = result.y;
  44219. var v = result.z;
  44220. //define bbox size within face
  44221. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  44222. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  44223. filterExtents[faceIdx].clampMin(0, 0, 0);
  44224. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  44225. //u and v extent in face corresponding to center tap
  44226. var minU = filterExtents[faceIdx].min.x;
  44227. var minV = filterExtents[faceIdx].min.y;
  44228. var maxU = filterExtents[faceIdx].max.x;
  44229. var maxV = filterExtents[faceIdx].max.y;
  44230. //bleed over amounts for face across u=0 edge (left)
  44231. bleedOverAmount[0] = (bboxSize - u);
  44232. bleedOverBBoxMin[0] = minV;
  44233. bleedOverBBoxMax[0] = maxV;
  44234. //bleed over amounts for face across u=1 edge (right)
  44235. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  44236. bleedOverBBoxMin[1] = minV;
  44237. bleedOverBBoxMax[1] = maxV;
  44238. //bleed over to face across v=0 edge (up)
  44239. bleedOverAmount[2] = (bboxSize - v);
  44240. bleedOverBBoxMin[2] = minU;
  44241. bleedOverBBoxMax[2] = maxU;
  44242. //bleed over to face across v=1 edge (down)
  44243. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  44244. bleedOverBBoxMin[3] = minU;
  44245. bleedOverBBoxMax[3] = maxU;
  44246. //compute bleed over regions in neighboring faces
  44247. for (var i = 0; i < 4; i++) {
  44248. if (bleedOverAmount[i] > 0) {
  44249. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  44250. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  44251. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  44252. // be flipped: the cases are
  44253. // if a left edge mates with a left or bottom edge on the neighbor
  44254. // if a top edge mates with a top or right edge on the neighbor
  44255. // if a right edge mates with a right or top edge on the neighbor
  44256. // if a bottom edge mates with a bottom or left edge on the neighbor
  44257. //Seeing as the edges are enumerated as follows
  44258. // left =0
  44259. // right =1
  44260. // top =2
  44261. // bottom =3
  44262. //
  44263. // so if the edge enums are the same, or the sum of the enums == 3,
  44264. // the bbox needs to be flipped
  44265. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  44266. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  44267. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  44268. }
  44269. //The way the bounding box is extended onto the neighboring face
  44270. // depends on which edge of neighboring face abuts with this one
  44271. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  44272. case PMREMGenerator.CP_EDGE_LEFT:
  44273. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  44274. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  44275. break;
  44276. case PMREMGenerator.CP_EDGE_RIGHT:
  44277. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  44278. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  44279. break;
  44280. case PMREMGenerator.CP_EDGE_TOP:
  44281. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  44282. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  44283. break;
  44284. case PMREMGenerator.CP_EDGE_BOTTOM:
  44285. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  44286. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  44287. break;
  44288. }
  44289. //clamp filter extents in non-center tap faces to remain within surface
  44290. filterExtents[neighborFace].clampMin(0, 0, 0);
  44291. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  44292. }
  44293. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  44294. // from the center tap face, then process the opposite face entirely for now.
  44295. //Note that the cases in which this happens, what usually happens is that
  44296. // more than one edge bleeds onto the opposite face, and the bounding box
  44297. // encompasses the entire cube map face.
  44298. if (bleedOverAmount[i] > srcSize) {
  44299. //determine opposite face
  44300. switch (faceIdx) {
  44301. case PMREMGenerator.CP_FACE_X_POS:
  44302. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  44303. break;
  44304. case PMREMGenerator.CP_FACE_X_NEG:
  44305. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  44306. break;
  44307. case PMREMGenerator.CP_FACE_Y_POS:
  44308. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  44309. break;
  44310. case PMREMGenerator.CP_FACE_Y_NEG:
  44311. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  44312. break;
  44313. case PMREMGenerator.CP_FACE_Z_POS:
  44314. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  44315. break;
  44316. case PMREMGenerator.CP_FACE_Z_NEG:
  44317. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  44318. break;
  44319. default:
  44320. break;
  44321. }
  44322. //just encompass entire face for now
  44323. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  44324. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  44325. }
  44326. }
  44327. };
  44328. //--------------------------------------------------------------------------------------
  44329. //ProcessFilterExtents
  44330. // Process bounding box in each cube face
  44331. //
  44332. //--------------------------------------------------------------------------------------
  44333. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  44334. //accumulators are 64-bit floats in order to have the precision needed
  44335. // over a summation of a large number of pixels
  44336. var dstAccum = [0, 0, 0, 0];
  44337. var weightAccum = 0;
  44338. var k = 0;
  44339. var nSrcChannels = this.numChannels;
  44340. // norm cube map and srcCubeMap have same face width
  44341. var faceWidth = srcSize;
  44342. //amount to add to pointer to move to next scanline in images
  44343. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  44344. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  44345. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  44346. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  44347. // iterate over cubefaces
  44348. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  44349. //if bbox is non empty
  44350. if (!filterExtents[iFaceIdx].empty()) {
  44351. var uStart = filterExtents[iFaceIdx].min.x;
  44352. var vStart = filterExtents[iFaceIdx].min.y;
  44353. var uEnd = filterExtents[iFaceIdx].max.x;
  44354. var vEnd = filterExtents[iFaceIdx].max.y;
  44355. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  44356. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  44357. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  44358. for (var v = vStart; v <= vEnd; v++) {
  44359. var normCubeRowWalk = 0;
  44360. var srcCubeRowWalk = 0;
  44361. for (var u = uStart; u <= uEnd; u++) {
  44362. //pointer to direction in cube map associated with texel
  44363. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  44364. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  44365. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  44366. //check dot product to see if texel is within cone
  44367. var tapDotProd = texelVectX * centerTapDir.x +
  44368. texelVectY * centerTapDir.y +
  44369. texelVectZ * centerTapDir.z;
  44370. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  44371. //solid angle stored in 4th channel of normalizer/solid angle cube map
  44372. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  44373. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  44374. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  44375. // so just adding one to specularpower do the trick.
  44376. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  44377. //iterate over channels
  44378. for (k = 0; k < nSrcChannels; k++) {
  44379. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  44380. srcCubeRowWalk++;
  44381. }
  44382. weightAccum += weight; //accumulate weight
  44383. }
  44384. else {
  44385. //step across source pixel
  44386. srcCubeRowWalk += nSrcChannels;
  44387. }
  44388. normCubeRowWalk += 4; // 4 channels per norm cube map.
  44389. }
  44390. startIndexNormCubeMap += normCubePitch;
  44391. startIndexSrcCubeMap += srcCubePitch;
  44392. }
  44393. }
  44394. }
  44395. //divide through by weights if weight is non zero
  44396. if (weightAccum != 0.0) {
  44397. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  44398. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  44399. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  44400. if (this.numChannels > 3) {
  44401. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  44402. }
  44403. }
  44404. else {
  44405. // otherwise sample nearest
  44406. // get face idx and u, v texel coordinate in face
  44407. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  44408. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  44409. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  44410. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  44411. if (this.numChannels > 3) {
  44412. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  44413. }
  44414. }
  44415. return PMREMGenerator._vectorTemp;
  44416. };
  44417. //--------------------------------------------------------------------------------------
  44418. // Fixup cube edges
  44419. //
  44420. // average texels on cube map faces across the edges
  44421. // WARP/BENT Method Only.
  44422. //--------------------------------------------------------------------------------------
  44423. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  44424. var k;
  44425. var j;
  44426. var i;
  44427. var iFace;
  44428. var iCorner = 0;
  44429. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  44430. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  44431. // note that if functionality to filter across the three texels for each corner, then
  44432. //indexed by corner and face idx. the array contains the face the start points belongs to.
  44433. var cornerPtr = [
  44434. [[], [], []],
  44435. [[], [], []],
  44436. [[], [], []],
  44437. [[], [], []],
  44438. [[], [], []],
  44439. [[], [], []],
  44440. [[], [], []],
  44441. [[], [], []]
  44442. ];
  44443. //if there is no fixup, or fixup width = 0, do nothing
  44444. if (cubeMapSize < 1) {
  44445. return;
  44446. }
  44447. //special case 1x1 cubemap, average face colors
  44448. if (cubeMapSize == 1) {
  44449. //iterate over channels
  44450. for (k = 0; k < this.numChannels; k++) {
  44451. var accum = 0.0;
  44452. //iterate over faces to accumulate face colors
  44453. for (iFace = 0; iFace < 6; iFace++) {
  44454. accum += cubeMap[iFace][k];
  44455. }
  44456. //compute average over 6 face colors
  44457. accum /= 6.0;
  44458. //iterate over faces to distribute face colors
  44459. for (iFace = 0; iFace < 6; iFace++) {
  44460. cubeMap[iFace][k] = accum;
  44461. }
  44462. }
  44463. return;
  44464. }
  44465. //iterate over faces to collect list of corner texel pointers
  44466. for (iFace = 0; iFace < 6; iFace++) {
  44467. //the 4 corner pointers for this face
  44468. faceCornerStartIndicies[0] = [iFace, 0];
  44469. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  44470. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  44471. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  44472. //iterate over face corners to collect cube corner pointers
  44473. for (iCorner = 0; iCorner < 4; iCorner++) {
  44474. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  44475. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  44476. cornerNumPtrs[corner]++;
  44477. }
  44478. }
  44479. //iterate over corners to average across corner tap values
  44480. for (iCorner = 0; iCorner < 8; iCorner++) {
  44481. for (k = 0; k < this.numChannels; k++) {
  44482. var cornerTapAccum = 0.0;
  44483. //iterate over corner texels and average results
  44484. for (i = 0; i < 3; i++) {
  44485. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  44486. }
  44487. //divide by 3 to compute average of corner tap values
  44488. cornerTapAccum *= (1.0 / 3.0);
  44489. //iterate over corner texels and average results
  44490. for (i = 0; i < 3; i++) {
  44491. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  44492. }
  44493. }
  44494. }
  44495. //iterate over the twelve edges of the cube to average across edges
  44496. for (i = 0; i < 12; i++) {
  44497. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  44498. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  44499. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  44500. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  44501. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  44502. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  44503. var edgeWalk = 0;
  44504. var neighborEdgeWalk = 0;
  44505. //Determine walking pointers based on edge type
  44506. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  44507. switch (edge) {
  44508. case PMREMGenerator.CP_EDGE_LEFT:
  44509. // no change to faceEdgeStartPtr
  44510. edgeWalk = this.numChannels * cubeMapSize;
  44511. break;
  44512. case PMREMGenerator.CP_EDGE_RIGHT:
  44513. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44514. edgeWalk = this.numChannels * cubeMapSize;
  44515. break;
  44516. case PMREMGenerator.CP_EDGE_TOP:
  44517. // no change to faceEdgeStartPtr
  44518. edgeWalk = this.numChannels;
  44519. break;
  44520. case PMREMGenerator.CP_EDGE_BOTTOM:
  44521. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  44522. edgeWalk = this.numChannels;
  44523. break;
  44524. }
  44525. //For certain types of edge abutments, the neighbor edge walk needs to
  44526. // be flipped: the cases are
  44527. // if a left edge mates with a left or bottom edge on the neighbor
  44528. // if a top edge mates with a top or right edge on the neighbor
  44529. // if a right edge mates with a right or top edge on the neighbor
  44530. // if a bottom edge mates with a bottom or left edge on the neighbor
  44531. //Seeing as the edges are enumerated as follows
  44532. // left =0
  44533. // right =1
  44534. // top =2
  44535. // bottom =3
  44536. //
  44537. //If the edge enums are the same, or the sum of the enums == 3,
  44538. // the neighbor edge walk needs to be flipped
  44539. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  44540. switch (neighborEdge) {
  44541. case PMREMGenerator.CP_EDGE_LEFT:
  44542. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  44543. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  44544. break;
  44545. case PMREMGenerator.CP_EDGE_RIGHT:
  44546. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  44547. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  44548. break;
  44549. case PMREMGenerator.CP_EDGE_TOP:
  44550. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44551. neighborEdgeWalk = -this.numChannels;
  44552. break;
  44553. case PMREMGenerator.CP_EDGE_BOTTOM:
  44554. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  44555. neighborEdgeWalk = -this.numChannels;
  44556. break;
  44557. }
  44558. }
  44559. else {
  44560. //swapped direction neighbor edge walk
  44561. switch (neighborEdge) {
  44562. case PMREMGenerator.CP_EDGE_LEFT:
  44563. //no change to neighborEdgeStartPtr for this case since it points
  44564. // to the upper left corner already
  44565. neighborEdgeWalk = this.numChannels * cubeMapSize;
  44566. break;
  44567. case PMREMGenerator.CP_EDGE_RIGHT:
  44568. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  44569. neighborEdgeWalk = this.numChannels * cubeMapSize;
  44570. break;
  44571. case PMREMGenerator.CP_EDGE_TOP:
  44572. //no change to neighborEdgeStartPtr for this case since it points
  44573. // to the upper left corner already
  44574. neighborEdgeWalk = this.numChannels;
  44575. break;
  44576. case PMREMGenerator.CP_EDGE_BOTTOM:
  44577. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  44578. neighborEdgeWalk = this.numChannels;
  44579. break;
  44580. }
  44581. }
  44582. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  44583. //nearby neighborhood
  44584. //step ahead one texel on edge
  44585. edgeStartIndex += edgeWalk;
  44586. neighborEdgeStartIndex += neighborEdgeWalk;
  44587. // note that this loop does not process the corner texels, since they have already been
  44588. // averaged across faces across earlier
  44589. for (j = 1; j < (cubeMapSize - 1); j++) {
  44590. //for each set of taps along edge, average them
  44591. // and rewrite the results into the edges
  44592. for (k = 0; k < this.numChannels; k++) {
  44593. var edgeTap = cubeMap[face][edgeStartIndex + k];
  44594. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  44595. //compute average of tap intensity values
  44596. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  44597. //propagate average of taps to edge taps
  44598. cubeMap[face][edgeStartIndex + k] = avgTap;
  44599. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  44600. }
  44601. edgeStartIndex += edgeWalk;
  44602. neighborEdgeStartIndex += neighborEdgeWalk;
  44603. }
  44604. }
  44605. };
  44606. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  44607. PMREMGenerator.CP_UDIR = 0;
  44608. PMREMGenerator.CP_VDIR = 1;
  44609. PMREMGenerator.CP_FACEAXIS = 2;
  44610. //used to index cube faces
  44611. PMREMGenerator.CP_FACE_X_POS = 0;
  44612. PMREMGenerator.CP_FACE_X_NEG = 1;
  44613. PMREMGenerator.CP_FACE_Y_POS = 2;
  44614. PMREMGenerator.CP_FACE_Y_NEG = 3;
  44615. PMREMGenerator.CP_FACE_Z_POS = 4;
  44616. PMREMGenerator.CP_FACE_Z_NEG = 5;
  44617. //used to index image edges
  44618. // NOTE.. the actual number corresponding to the edge is important
  44619. // do not change these, or the code will break
  44620. //
  44621. // CP_EDGE_LEFT is u = 0
  44622. // CP_EDGE_RIGHT is u = width-1
  44623. // CP_EDGE_TOP is v = 0
  44624. // CP_EDGE_BOTTOM is v = height-1
  44625. PMREMGenerator.CP_EDGE_LEFT = 0;
  44626. PMREMGenerator.CP_EDGE_RIGHT = 1;
  44627. PMREMGenerator.CP_EDGE_TOP = 2;
  44628. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  44629. //corners of CUBE map (P or N specifys if it corresponds to the
  44630. // positive or negative direction each of X, Y, and Z
  44631. PMREMGenerator.CP_CORNER_NNN = 0;
  44632. PMREMGenerator.CP_CORNER_NNP = 1;
  44633. PMREMGenerator.CP_CORNER_NPN = 2;
  44634. PMREMGenerator.CP_CORNER_NPP = 3;
  44635. PMREMGenerator.CP_CORNER_PNN = 4;
  44636. PMREMGenerator.CP_CORNER_PNP = 5;
  44637. PMREMGenerator.CP_CORNER_PPN = 6;
  44638. PMREMGenerator.CP_CORNER_PPP = 7;
  44639. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  44640. //3x2 matrices that map cube map indexing vectors in 3d
  44641. // (after face selection and divide through by the
  44642. // _ABSOLUTE VALUE_ of the max coord)
  44643. // into NVC space
  44644. //Note this currently assumes the D3D cube face ordering and orientation
  44645. PMREMGenerator._sgFace2DMapping = [
  44646. //XPOS face
  44647. [[0, 0, -1],
  44648. [0, -1, 0],
  44649. [1, 0, 0]],
  44650. //XNEG face
  44651. [[0, 0, 1],
  44652. [0, -1, 0],
  44653. [-1, 0, 0]],
  44654. //YPOS face
  44655. [[1, 0, 0],
  44656. [0, 0, 1],
  44657. [0, 1, 0]],
  44658. //YNEG face
  44659. [[1, 0, 0],
  44660. [0, 0, -1],
  44661. [0, -1, 0]],
  44662. //ZPOS face
  44663. [[1, 0, 0],
  44664. [0, -1, 0],
  44665. [0, 0, 1]],
  44666. //ZNEG face
  44667. [[-1, 0, 0],
  44668. [0, -1, 0],
  44669. [0, 0, -1]],
  44670. ];
  44671. //------------------------------------------------------------------------------
  44672. // D3D cube map face specification
  44673. // mapping from 3D x,y,z cube map lookup coordinates
  44674. // to 2D within face u,v coordinates
  44675. //
  44676. // --------------------> U direction
  44677. // | (within-face texture space)
  44678. // | _____
  44679. // | | |
  44680. // | | +Y |
  44681. // | _____|_____|_____ _____
  44682. // | | | | | |
  44683. // | | -X | +Z | +X | -Z |
  44684. // | |_____|_____|_____|_____|
  44685. // | | |
  44686. // | | -Y |
  44687. // | |_____|
  44688. // |
  44689. // v V direction
  44690. // (within-face texture space)
  44691. //------------------------------------------------------------------------------
  44692. //Information about neighbors and how texture coorrdinates change across faces
  44693. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  44694. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  44695. //Note this currently assumes the D3D cube face ordering and orientation
  44696. PMREMGenerator._sgCubeNgh = [
  44697. //XPOS face
  44698. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44699. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44700. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44701. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  44702. //XNEG face
  44703. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44704. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  44705. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  44706. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  44707. //YPOS face
  44708. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  44709. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  44710. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  44711. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  44712. //YNEG face
  44713. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  44714. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44715. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44716. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  44717. //ZPOS face
  44718. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44719. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  44720. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44721. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  44722. //ZNEG face
  44723. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44724. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44725. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  44726. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  44727. ];
  44728. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  44729. // this table is used to average over the edges.
  44730. PMREMGenerator._sgCubeEdgeList = [
  44731. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  44732. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  44733. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  44734. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44735. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  44736. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  44737. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  44738. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  44739. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  44740. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  44741. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  44742. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  44743. ];
  44744. //Information about which of the 8 cube corners are correspond to the
  44745. // the 4 corners in each cube face
  44746. // the order is upper left, upper right, lower left, lower right
  44747. PMREMGenerator._sgCubeCornerList = [
  44748. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  44749. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  44750. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  44751. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  44752. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  44753. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  44754. ];
  44755. return PMREMGenerator;
  44756. })();
  44757. Internals.PMREMGenerator = PMREMGenerator;
  44758. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  44759. })(BABYLON || (BABYLON = {}));
  44760. var BABYLON;
  44761. (function (BABYLON) {
  44762. /**
  44763. * This represents a texture coming from an HDR input.
  44764. *
  44765. * The only supported format is currently panorama picture stored in RGBE format.
  44766. * Example of such files can be found on HDRLib: http://hdrlib.com/
  44767. */
  44768. var HDRCubeTexture = (function (_super) {
  44769. __extends(HDRCubeTexture, _super);
  44770. /**
  44771. * Instantiates an HDRTexture from the following parameters.
  44772. *
  44773. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  44774. * @param scene The scene the texture will be used in
  44775. * @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.
  44776. * @param noMipmap Forces to not generate the mipmap if true
  44777. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  44778. * @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)
  44779. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  44780. */
  44781. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  44782. if (noMipmap === void 0) { noMipmap = false; }
  44783. if (generateHarmonics === void 0) { generateHarmonics = true; }
  44784. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  44785. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  44786. _super.call(this, scene);
  44787. this._useInGammaSpace = false;
  44788. this._generateHarmonics = true;
  44789. this._isBABYLONPreprocessed = false;
  44790. /**
  44791. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  44792. */
  44793. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  44794. /**
  44795. * The spherical polynomial data extracted from the texture.
  44796. */
  44797. this.sphericalPolynomial = null;
  44798. /**
  44799. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  44800. * This is usefull at run time to apply the good shader.
  44801. */
  44802. this.isPMREM = false;
  44803. if (!url) {
  44804. return;
  44805. }
  44806. this.name = url;
  44807. this.url = url;
  44808. this.hasAlpha = false;
  44809. this.isCube = true;
  44810. this._textureMatrix = BABYLON.Matrix.Identity();
  44811. if (size) {
  44812. this._isBABYLONPreprocessed = false;
  44813. this._noMipmap = noMipmap;
  44814. this._size = size;
  44815. this._useInGammaSpace = useInGammaSpace;
  44816. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  44817. }
  44818. else {
  44819. this._isBABYLONPreprocessed = true;
  44820. this._noMipmap = false;
  44821. this._useInGammaSpace = false;
  44822. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD;
  44823. }
  44824. this.isPMREM = this._usePMREMGenerator;
  44825. this._texture = this._getFromCache(url, this._noMipmap);
  44826. if (!this._texture) {
  44827. if (!scene.useDelayedTextureLoading) {
  44828. this.loadTexture();
  44829. }
  44830. else {
  44831. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  44832. }
  44833. }
  44834. }
  44835. /**
  44836. * Occurs when the file is a preprocessed .babylon.hdr file.
  44837. */
  44838. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  44839. var _this = this;
  44840. var mipLevels = 0;
  44841. var floatArrayView = null;
  44842. var mipmapGenerator = function (data) {
  44843. var mips = [];
  44844. var startIndex = 30;
  44845. for (var level = 0; level < mipLevels; level++) {
  44846. mips.push([]);
  44847. // Fill each pixel of the mip level.
  44848. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  44849. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44850. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  44851. mips[level].push(faceData);
  44852. startIndex += faceSize;
  44853. }
  44854. }
  44855. return mips;
  44856. };
  44857. var callback = function (buffer) {
  44858. // Create Native Array Views
  44859. var intArrayView = new Int32Array(buffer);
  44860. floatArrayView = new Float32Array(buffer);
  44861. // Fill header.
  44862. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  44863. _this._size = intArrayView[1]; // CubeMap max mip face size.
  44864. // Update Texture Information.
  44865. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  44866. // Fill polynomial information.
  44867. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  44868. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  44869. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  44870. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  44871. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  44872. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  44873. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  44874. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  44875. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  44876. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  44877. // Fill pixel data.
  44878. mipLevels = intArrayView[29]; // Number of mip levels.
  44879. var startIndex = 30;
  44880. var data = [];
  44881. var faceSize = Math.pow(_this._size, 2) * 3;
  44882. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44883. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  44884. }
  44885. var results = [];
  44886. var byteArray = null;
  44887. // Create uintarray fallback.
  44888. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  44889. // 3 channels of 1 bytes per pixel in bytes.
  44890. var byteBuffer = new ArrayBuffer(faceSize);
  44891. byteArray = new Uint8Array(byteBuffer);
  44892. mipmapGenerator = null;
  44893. }
  44894. // Push each faces.
  44895. for (var j = 0; j < 6; j++) {
  44896. var dataFace = data[j];
  44897. // If special cases.
  44898. if (_this._useInGammaSpace || byteArray) {
  44899. for (var i = 0; i < _this._size * _this._size; i++) {
  44900. // Put in gamma space if requested.
  44901. if (_this._useInGammaSpace) {
  44902. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  44903. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  44904. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  44905. }
  44906. // Convert to int texture for fallback.
  44907. if (byteArray) {
  44908. // R
  44909. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  44910. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  44911. // G
  44912. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  44913. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  44914. // B
  44915. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  44916. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  44917. }
  44918. }
  44919. }
  44920. results.push(dataFace);
  44921. }
  44922. return results;
  44923. };
  44924. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  44925. };
  44926. /**
  44927. * Occurs when the file is raw .hdr file.
  44928. */
  44929. HDRCubeTexture.prototype.loadHDRTexture = function () {
  44930. var _this = this;
  44931. var callback = function (buffer) {
  44932. // Extract the raw linear data.
  44933. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  44934. // Generate harmonics if needed.
  44935. if (_this._generateHarmonics) {
  44936. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  44937. }
  44938. var results = [];
  44939. var byteArray = null;
  44940. // Create uintarray fallback.
  44941. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  44942. // 3 channels of 1 bytes per pixel in bytes.
  44943. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  44944. byteArray = new Uint8Array(byteBuffer);
  44945. }
  44946. // Push each faces.
  44947. for (var j = 0; j < 6; j++) {
  44948. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  44949. // If special cases.
  44950. if (_this._useInGammaSpace || byteArray) {
  44951. for (var i = 0; i < _this._size * _this._size; i++) {
  44952. // Put in gamma space if requested.
  44953. if (_this._useInGammaSpace) {
  44954. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  44955. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  44956. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  44957. }
  44958. // Convert to int texture for fallback.
  44959. if (byteArray) {
  44960. // R
  44961. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  44962. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  44963. // G
  44964. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  44965. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  44966. // B
  44967. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  44968. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  44969. }
  44970. }
  44971. }
  44972. results.push(dataFace);
  44973. }
  44974. return results;
  44975. };
  44976. var mipmapGenerator = null;
  44977. if (!this._noMipmap && this._usePMREMGenerator) {
  44978. mipmapGenerator = function (data) {
  44979. // Custom setup of the generator matching with the PBR shader values.
  44980. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  44981. return generator.filterCubeMap();
  44982. };
  44983. }
  44984. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  44985. };
  44986. /**
  44987. * Starts the loading process of the texture.
  44988. */
  44989. HDRCubeTexture.prototype.loadTexture = function () {
  44990. if (this._isBABYLONPreprocessed) {
  44991. this.loadBabylonTexture();
  44992. }
  44993. else {
  44994. this.loadHDRTexture();
  44995. }
  44996. };
  44997. HDRCubeTexture.prototype.clone = function () {
  44998. var size = this._isBABYLONPreprocessed ? null : this._size;
  44999. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  45000. // Base texture
  45001. newTexture.level = this.level;
  45002. newTexture.wrapU = this.wrapU;
  45003. newTexture.wrapV = this.wrapV;
  45004. newTexture.coordinatesIndex = this.coordinatesIndex;
  45005. newTexture.coordinatesMode = this.coordinatesMode;
  45006. return newTexture;
  45007. };
  45008. // Methods
  45009. HDRCubeTexture.prototype.delayLoad = function () {
  45010. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45011. return;
  45012. }
  45013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45014. this._texture = this._getFromCache(this.url, this._noMipmap);
  45015. if (!this._texture) {
  45016. this.loadTexture();
  45017. }
  45018. };
  45019. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  45020. return this._textureMatrix;
  45021. };
  45022. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45023. var texture = null;
  45024. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  45025. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  45026. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  45027. texture.name = parsedTexture.name;
  45028. texture.hasAlpha = parsedTexture.hasAlpha;
  45029. texture.level = parsedTexture.level;
  45030. texture.coordinatesMode = parsedTexture.coordinatesMode;
  45031. }
  45032. return texture;
  45033. };
  45034. HDRCubeTexture.prototype.serialize = function () {
  45035. if (!this.name) {
  45036. return null;
  45037. }
  45038. var serializationObject = {};
  45039. serializationObject.name = this.name;
  45040. serializationObject.hasAlpha = this.hasAlpha;
  45041. serializationObject.isCube = true;
  45042. serializationObject.level = this.level;
  45043. serializationObject.size = this._size;
  45044. serializationObject.coordinatesMode = this.coordinatesMode;
  45045. serializationObject.useInGammaSpace = this._useInGammaSpace;
  45046. serializationObject.generateHarmonics = this._generateHarmonics;
  45047. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  45048. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  45049. return serializationObject;
  45050. };
  45051. /**
  45052. * Saves as a file the data contained in the texture in a binary format.
  45053. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  45054. * as the spherical used in the lighting.
  45055. * @param url The HDR file url.
  45056. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  45057. * @param onError Method called if any error happens during download.
  45058. * @return The packed binary data.
  45059. */
  45060. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  45061. if (onError === void 0) { onError = null; }
  45062. var callback = function (buffer) {
  45063. var data = new Blob([buffer], { type: 'application/octet-stream' });
  45064. // Returns a URL you can use as a href.
  45065. var objUrl = window.URL.createObjectURL(data);
  45066. // Simulates a link to it and click to dowload.
  45067. var a = document.createElement("a");
  45068. document.body.appendChild(a);
  45069. a.style.display = "none";
  45070. a.href = objUrl;
  45071. a.download = "envmap.babylon.hdr";
  45072. a.click();
  45073. };
  45074. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  45075. };
  45076. /**
  45077. * Serializes the data contained in the texture in a binary format.
  45078. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  45079. * as the spherical used in the lighting.
  45080. * @param url The HDR file url.
  45081. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  45082. * @param onError Method called if any error happens during download.
  45083. * @return The packed binary data.
  45084. */
  45085. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  45086. if (onError === void 0) { onError = null; }
  45087. // Needs the url tho create the texture.
  45088. if (!url) {
  45089. return null;
  45090. }
  45091. // Check Power of two size.
  45092. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  45093. return null;
  45094. }
  45095. var getDataCallback = function (dataBuffer) {
  45096. // Extract the raw linear data.
  45097. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  45098. // Generate harmonics if needed.
  45099. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  45100. // Generate seamless faces
  45101. var mipGeneratorArray = [];
  45102. // Data are known to be in +X +Y +Z -X -Y -Z
  45103. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  45104. mipGeneratorArray.push(cubeData.right); // +X
  45105. mipGeneratorArray.push(cubeData.left); // -X
  45106. mipGeneratorArray.push(cubeData.up); // +Y
  45107. mipGeneratorArray.push(cubeData.down); // -Y
  45108. mipGeneratorArray.push(cubeData.front); // +Z
  45109. mipGeneratorArray.push(cubeData.back); // -Z
  45110. // Custom setup of the generator matching with the PBR shader values.
  45111. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  45112. var mippedData = generator.filterCubeMap();
  45113. // Compute required byte length.
  45114. var byteLength = 1 * 4; // Raw Data Version int32.
  45115. byteLength += 4; // CubeMap max mip face size int32.
  45116. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  45117. // Add data size.
  45118. byteLength += 4; // Number of mip levels int32.
  45119. for (var level = 0; level < mippedData.length; level++) {
  45120. var mipSize = size >> level;
  45121. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  45122. }
  45123. // Prepare binary structure.
  45124. var buffer = new ArrayBuffer(byteLength);
  45125. var intArrayView = new Int32Array(buffer);
  45126. var floatArrayView = new Float32Array(buffer);
  45127. // Fill header.
  45128. intArrayView[0] = 1; // Version 1.
  45129. intArrayView[1] = size; // CubeMap max mip face size.
  45130. // Fill polynomial information.
  45131. sphericalPolynomial.x.toArray(floatArrayView, 2);
  45132. sphericalPolynomial.y.toArray(floatArrayView, 5);
  45133. sphericalPolynomial.z.toArray(floatArrayView, 8);
  45134. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  45135. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  45136. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  45137. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  45138. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  45139. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  45140. // Fill pixel data.
  45141. intArrayView[29] = mippedData.length; // Number of mip levels.
  45142. var startIndex = 30;
  45143. for (var level = 0; level < mippedData.length; level++) {
  45144. // Fill each pixel of the mip level.
  45145. var faceSize = Math.pow(size >> level, 2) * 3;
  45146. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45147. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  45148. startIndex += faceSize;
  45149. }
  45150. }
  45151. // Callback.
  45152. callback(buffer);
  45153. };
  45154. // Download and process.
  45155. BABYLON.Tools.LoadFile(url, function (data) {
  45156. getDataCallback(data);
  45157. }, null, null, true, onError);
  45158. };
  45159. HDRCubeTexture._facesMapping = [
  45160. "right",
  45161. "up",
  45162. "front",
  45163. "left",
  45164. "down",
  45165. "back"
  45166. ];
  45167. return HDRCubeTexture;
  45168. })(BABYLON.BaseTexture);
  45169. BABYLON.HDRCubeTexture = HDRCubeTexture;
  45170. })(BABYLON || (BABYLON = {}));
  45171. var BABYLON;
  45172. (function (BABYLON) {
  45173. var Debug;
  45174. (function (Debug) {
  45175. /**
  45176. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  45177. */
  45178. var SkeletonViewer = (function () {
  45179. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  45180. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  45181. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  45182. this.skeleton = skeleton;
  45183. this.mesh = mesh;
  45184. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  45185. this.renderingGroupId = renderingGroupId;
  45186. this.color = BABYLON.Color3.White();
  45187. this._debugLines = [];
  45188. this._isEnabled = false;
  45189. this._scene = scene;
  45190. this.update();
  45191. this._renderFunction = this.update.bind(this);
  45192. }
  45193. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  45194. get: function () {
  45195. return this._isEnabled;
  45196. },
  45197. set: function (value) {
  45198. if (this._isEnabled === value) {
  45199. return;
  45200. }
  45201. this._isEnabled = value;
  45202. if (value) {
  45203. this._scene.registerBeforeRender(this._renderFunction);
  45204. }
  45205. else {
  45206. this._scene.unregisterBeforeRender(this._renderFunction);
  45207. }
  45208. },
  45209. enumerable: true,
  45210. configurable: true
  45211. });
  45212. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  45213. if (x === void 0) { x = 0; }
  45214. if (y === void 0) { y = 0; }
  45215. if (z === void 0) { z = 0; }
  45216. var tmat = BABYLON.Tmp.Matrix[0];
  45217. var parentBone = bone.getParent();
  45218. tmat.copyFrom(bone.getLocalMatrix());
  45219. if (x !== 0 || y !== 0 || z !== 0) {
  45220. var tmat2 = BABYLON.Tmp.Matrix[1];
  45221. BABYLON.Matrix.IdentityToRef(tmat2);
  45222. tmat2.m[12] = x;
  45223. tmat2.m[13] = y;
  45224. tmat2.m[14] = z;
  45225. tmat2.multiplyToRef(tmat, tmat);
  45226. }
  45227. if (parentBone) {
  45228. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  45229. }
  45230. tmat.multiplyToRef(meshMat, tmat);
  45231. position.x = tmat.m[12];
  45232. position.y = tmat.m[13];
  45233. position.z = tmat.m[14];
  45234. };
  45235. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  45236. var len = bones.length;
  45237. for (var i = 0; i < len; i++) {
  45238. var bone = bones[i];
  45239. var points = this._debugLines[i];
  45240. if (!points) {
  45241. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45242. this._debugLines[i] = points;
  45243. }
  45244. this._getBonePosition(points[0], bone, meshMat);
  45245. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  45246. }
  45247. };
  45248. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  45249. var len = bones.length;
  45250. var boneNum = 0;
  45251. for (var i = len - 1; i >= 0; i--) {
  45252. var childBone = bones[i];
  45253. var parentBone = childBone.getParent();
  45254. if (!parentBone) {
  45255. continue;
  45256. }
  45257. var points = this._debugLines[boneNum];
  45258. if (!points) {
  45259. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45260. this._debugLines[boneNum] = points;
  45261. }
  45262. this._getBonePosition(points[0], childBone, meshMat);
  45263. this._getBonePosition(points[1], parentBone, meshMat);
  45264. boneNum++;
  45265. }
  45266. };
  45267. SkeletonViewer.prototype.update = function () {
  45268. if (this.autoUpdateBonesMatrices) {
  45269. this._updateBoneMatrix(this.skeleton.bones[0]);
  45270. }
  45271. if (this.skeleton.bones[0].length === undefined) {
  45272. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  45273. }
  45274. else {
  45275. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  45276. }
  45277. if (!this._debugMesh) {
  45278. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  45279. this._debugMesh.renderingGroupId = this.renderingGroupId;
  45280. }
  45281. else {
  45282. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  45283. }
  45284. this._debugMesh.color = this.color;
  45285. };
  45286. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  45287. if (bone.getParent()) {
  45288. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  45289. }
  45290. var children = bone.children;
  45291. var len = children.length;
  45292. for (var i = 0; i < len; i++) {
  45293. this._updateBoneMatrix(children[i]);
  45294. }
  45295. };
  45296. SkeletonViewer.prototype.dispose = function () {
  45297. if (this._debugMesh) {
  45298. this.isEnabled = false;
  45299. this._debugMesh.dispose();
  45300. this._debugMesh = null;
  45301. }
  45302. };
  45303. return SkeletonViewer;
  45304. })();
  45305. Debug.SkeletonViewer = SkeletonViewer;
  45306. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45307. })(BABYLON || (BABYLON = {}));
  45308. var BABYLON;
  45309. (function (BABYLON) {
  45310. var maxSimultaneousLights = 4;
  45311. var PBRMaterialDefines = (function (_super) {
  45312. __extends(PBRMaterialDefines, _super);
  45313. function PBRMaterialDefines() {
  45314. _super.call(this);
  45315. this.ALBEDO = false;
  45316. this.AMBIENT = false;
  45317. this.OPACITY = false;
  45318. this.OPACITYRGB = false;
  45319. this.REFLECTION = false;
  45320. this.EMISSIVE = false;
  45321. this.REFLECTIVITY = false;
  45322. this.BUMP = false;
  45323. this.PARALLAX = false;
  45324. this.PARALLAXOCCLUSION = false;
  45325. this.SPECULAROVERALPHA = false;
  45326. this.CLIPPLANE = false;
  45327. this.ALPHATEST = false;
  45328. this.ALPHAFROMALBEDO = false;
  45329. this.POINTSIZE = false;
  45330. this.FOG = false;
  45331. this.LIGHT0 = false;
  45332. this.LIGHT1 = false;
  45333. this.LIGHT2 = false;
  45334. this.LIGHT3 = false;
  45335. this.SPOTLIGHT0 = false;
  45336. this.SPOTLIGHT1 = false;
  45337. this.SPOTLIGHT2 = false;
  45338. this.SPOTLIGHT3 = false;
  45339. this.HEMILIGHT0 = false;
  45340. this.HEMILIGHT1 = false;
  45341. this.HEMILIGHT2 = false;
  45342. this.HEMILIGHT3 = false;
  45343. this.POINTLIGHT0 = false;
  45344. this.POINTLIGHT1 = false;
  45345. this.POINTLIGHT2 = false;
  45346. this.POINTLIGHT3 = false;
  45347. this.DIRLIGHT0 = false;
  45348. this.DIRLIGHT1 = false;
  45349. this.DIRLIGHT2 = false;
  45350. this.DIRLIGHT3 = false;
  45351. this.SPECULARTERM = false;
  45352. this.SHADOW0 = false;
  45353. this.SHADOW1 = false;
  45354. this.SHADOW2 = false;
  45355. this.SHADOW3 = false;
  45356. this.SHADOWS = false;
  45357. this.SHADOWVSM0 = false;
  45358. this.SHADOWVSM1 = false;
  45359. this.SHADOWVSM2 = false;
  45360. this.SHADOWVSM3 = false;
  45361. this.SHADOWPCF0 = false;
  45362. this.SHADOWPCF1 = false;
  45363. this.SHADOWPCF2 = false;
  45364. this.SHADOWPCF3 = false;
  45365. this.OPACITYFRESNEL = false;
  45366. this.EMISSIVEFRESNEL = false;
  45367. this.FRESNEL = false;
  45368. this.NORMAL = false;
  45369. this.UV1 = false;
  45370. this.UV2 = false;
  45371. this.VERTEXCOLOR = false;
  45372. this.VERTEXALPHA = false;
  45373. this.NUM_BONE_INFLUENCERS = 0;
  45374. this.BonesPerMesh = 0;
  45375. this.INSTANCES = false;
  45376. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  45377. this.MICROSURFACEAUTOMATIC = false;
  45378. this.EMISSIVEASILLUMINATION = false;
  45379. this.LINKEMISSIVEWITHALBEDO = false;
  45380. this.LIGHTMAP = false;
  45381. this.USELIGHTMAPASSHADOWMAP = false;
  45382. this.REFLECTIONMAP_3D = false;
  45383. this.REFLECTIONMAP_SPHERICAL = false;
  45384. this.REFLECTIONMAP_PLANAR = false;
  45385. this.REFLECTIONMAP_CUBIC = false;
  45386. this.REFLECTIONMAP_PROJECTION = false;
  45387. this.REFLECTIONMAP_SKYBOX = false;
  45388. this.REFLECTIONMAP_EXPLICIT = false;
  45389. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45390. this.INVERTCUBICMAP = false;
  45391. this.LOGARITHMICDEPTH = false;
  45392. this.CAMERATONEMAP = false;
  45393. this.CAMERACONTRAST = false;
  45394. this.OVERLOADEDVALUES = false;
  45395. this.OVERLOADEDSHADOWVALUES = false;
  45396. this.USESPHERICALFROMREFLECTIONMAP = false;
  45397. this.REFRACTION = false;
  45398. this.REFRACTIONMAP_3D = false;
  45399. this.LINKREFRACTIONTOTRANSPARENCY = false;
  45400. this.REFRACTIONMAPINLINEARSPACE = false;
  45401. this.LODBASEDMICROSFURACE = false;
  45402. this.USEPHYSICALLIGHTFALLOFF = false;
  45403. this.RADIANCEOVERALPHA = false;
  45404. this.USEPMREMREFLECTION = false;
  45405. this.USEPMREMREFRACTION = false;
  45406. this._keys = Object.keys(this);
  45407. }
  45408. return PBRMaterialDefines;
  45409. })(BABYLON.MaterialDefines);
  45410. /**
  45411. * The Physically based material of BJS.
  45412. *
  45413. * This offers the main features of a standard PBR material.
  45414. * For more information, please refer to the documentation :
  45415. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45416. */
  45417. var PBRMaterial = (function (_super) {
  45418. __extends(PBRMaterial, _super);
  45419. /**
  45420. * Instantiates a new PBRMaterial instance.
  45421. *
  45422. * @param name The material name
  45423. * @param scene The scene the material will be use in.
  45424. */
  45425. function PBRMaterial(name, scene) {
  45426. var _this = this;
  45427. _super.call(this, name, scene);
  45428. /**
  45429. * Intensity of the direct lights e.g. the four lights available in your scene.
  45430. * This impacts both the direct diffuse and specular highlights.
  45431. */
  45432. this.directIntensity = 1.0;
  45433. /**
  45434. * Intensity of the emissive part of the material.
  45435. * This helps controlling the emissive effect without modifying the emissive color.
  45436. */
  45437. this.emissiveIntensity = 1.0;
  45438. /**
  45439. * Intensity of the environment e.g. how much the environment will light the object
  45440. * either through harmonics for rough material or through the refelction for shiny ones.
  45441. */
  45442. this.environmentIntensity = 1.0;
  45443. /**
  45444. * This is a special control allowing the reduction of the specular highlights coming from the
  45445. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45446. */
  45447. this.specularIntensity = 1.0;
  45448. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  45449. /**
  45450. * Debug Control allowing disabling the bump map on this material.
  45451. */
  45452. this.disableBumpMap = false;
  45453. /**
  45454. * Debug Control helping enforcing or dropping the darkness of shadows.
  45455. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  45456. */
  45457. this.overloadedShadowIntensity = 1.0;
  45458. /**
  45459. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  45460. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  45461. */
  45462. this.overloadedShadeIntensity = 1.0;
  45463. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  45464. /**
  45465. * The camera exposure used on this material.
  45466. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45467. * This corresponds to a photographic exposure.
  45468. */
  45469. this.cameraExposure = 1.0;
  45470. /**
  45471. * The camera contrast used on this material.
  45472. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  45473. */
  45474. this.cameraContrast = 1.0;
  45475. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  45476. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  45477. /**
  45478. * Debug Control allowing to overload the ambient color.
  45479. * This as to be use with the overloadedAmbientIntensity parameter.
  45480. */
  45481. this.overloadedAmbient = BABYLON.Color3.White();
  45482. /**
  45483. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  45484. */
  45485. this.overloadedAmbientIntensity = 0.0;
  45486. /**
  45487. * Debug Control allowing to overload the albedo color.
  45488. * This as to be use with the overloadedAlbedoIntensity parameter.
  45489. */
  45490. this.overloadedAlbedo = BABYLON.Color3.White();
  45491. /**
  45492. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  45493. */
  45494. this.overloadedAlbedoIntensity = 0.0;
  45495. /**
  45496. * Debug Control allowing to overload the reflectivity color.
  45497. * This as to be use with the overloadedReflectivityIntensity parameter.
  45498. */
  45499. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  45500. /**
  45501. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  45502. */
  45503. this.overloadedReflectivityIntensity = 0.0;
  45504. /**
  45505. * Debug Control allowing to overload the emissive color.
  45506. * This as to be use with the overloadedEmissiveIntensity parameter.
  45507. */
  45508. this.overloadedEmissive = BABYLON.Color3.White();
  45509. /**
  45510. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  45511. */
  45512. this.overloadedEmissiveIntensity = 0.0;
  45513. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  45514. /**
  45515. * Debug Control allowing to overload the reflection color.
  45516. * This as to be use with the overloadedReflectionIntensity parameter.
  45517. */
  45518. this.overloadedReflection = BABYLON.Color3.White();
  45519. /**
  45520. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  45521. */
  45522. this.overloadedReflectionIntensity = 0.0;
  45523. /**
  45524. * Debug Control allowing to overload the microsurface.
  45525. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  45526. */
  45527. this.overloadedMicroSurface = 0.0;
  45528. /**
  45529. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  45530. */
  45531. this.overloadedMicroSurfaceIntensity = 0.0;
  45532. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  45533. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45534. /**
  45535. * AKA Diffuse Color in other nomenclature.
  45536. */
  45537. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45538. /**
  45539. * AKA Specular Color in other nomenclature.
  45540. */
  45541. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45542. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  45543. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45544. /**
  45545. * AKA Glossiness in other nomenclature.
  45546. */
  45547. this.microSurface = 0.9;
  45548. /**
  45549. * source material index of refraction (IOR)' / 'destination material IOR.
  45550. */
  45551. this.indexOfRefraction = 0.66;
  45552. /**
  45553. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45554. */
  45555. this.invertRefractionY = false;
  45556. /**
  45557. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45558. * Materials half opaque for instance using refraction could benefit from this control.
  45559. */
  45560. this.linkRefractionWithTransparency = false;
  45561. /**
  45562. * The emissive and albedo are linked to never be more than one (Energy conservation).
  45563. */
  45564. this.linkEmissiveWithAlbedo = false;
  45565. this.useLightmapAsShadowmap = false;
  45566. /**
  45567. * In this mode, the emissive informtaion will always be added to the lighting once.
  45568. * A light for instance can be thought as emissive.
  45569. */
  45570. this.useEmissiveAsIllumination = false;
  45571. /**
  45572. * Secifies that the alpha is coming form the albedo channel alpha channel.
  45573. */
  45574. this.useAlphaFromAlbedoTexture = false;
  45575. /**
  45576. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45577. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45578. */
  45579. this.useSpecularOverAlpha = true;
  45580. /**
  45581. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45582. */
  45583. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45584. /**
  45585. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45586. * The material will try to infer what glossiness each pixel should be.
  45587. */
  45588. this.useAutoMicroSurfaceFromReflectivityMap = false;
  45589. /**
  45590. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  45591. * the creation of the material.
  45592. */
  45593. this.useScalarInLinearSpace = false;
  45594. /**
  45595. * BJS is using an harcoded light falloff based on a manually sets up range.
  45596. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45597. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45598. */
  45599. this.usePhysicalLightFalloff = true;
  45600. /**
  45601. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45602. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45603. */
  45604. this.useRadianceOverAlpha = true;
  45605. /**
  45606. * Allows using the bump map in parallax mode.
  45607. */
  45608. this.useParallax = false;
  45609. /**
  45610. * Allows using the bump map in parallax occlusion mode.
  45611. */
  45612. this.useParallaxOcclusion = false;
  45613. /**
  45614. * Controls the scale bias of the parallax mode.
  45615. */
  45616. this.parallaxScaleBias = 0.05;
  45617. this.disableLighting = false;
  45618. this._renderTargets = new BABYLON.SmartArray(16);
  45619. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  45620. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45621. this._tempColor = new BABYLON.Color3();
  45622. this._defines = new PBRMaterialDefines();
  45623. this._cachedDefines = new PBRMaterialDefines();
  45624. this._myScene = null;
  45625. this._myShadowGenerator = null;
  45626. this._cachedDefines.BonesPerMesh = -1;
  45627. this.getRenderTargetTextures = function () {
  45628. _this._renderTargets.reset();
  45629. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  45630. _this._renderTargets.push(_this.reflectionTexture);
  45631. }
  45632. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  45633. _this._renderTargets.push(_this.refractionTexture);
  45634. }
  45635. return _this._renderTargets;
  45636. };
  45637. }
  45638. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  45639. get: function () {
  45640. return this._useLogarithmicDepth;
  45641. },
  45642. set: function (value) {
  45643. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45644. },
  45645. enumerable: true,
  45646. configurable: true
  45647. });
  45648. PBRMaterial.prototype.needAlphaBlending = function () {
  45649. if (this.linkRefractionWithTransparency) {
  45650. return false;
  45651. }
  45652. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  45653. };
  45654. PBRMaterial.prototype.needAlphaTesting = function () {
  45655. if (this.linkRefractionWithTransparency) {
  45656. return false;
  45657. }
  45658. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  45659. };
  45660. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45661. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  45662. };
  45663. PBRMaterial.prototype.getAlphaTestTexture = function () {
  45664. return this.albedoTexture;
  45665. };
  45666. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  45667. if (!mesh) {
  45668. return true;
  45669. }
  45670. if (this._defines.INSTANCES !== useInstances) {
  45671. return false;
  45672. }
  45673. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  45674. return true;
  45675. }
  45676. return false;
  45677. };
  45678. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  45679. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  45680. };
  45681. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  45682. if (!useScalarInLinear) {
  45683. color.toLinearSpaceToRef(ref);
  45684. }
  45685. else {
  45686. ref.r = color.r;
  45687. ref.g = color.g;
  45688. ref.b = color.b;
  45689. }
  45690. };
  45691. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  45692. var lightIndex = 0;
  45693. var depthValuesAlreadySet = false;
  45694. for (var index = 0; index < scene.lights.length; index++) {
  45695. var light = scene.lights[index];
  45696. if (!light.isEnabled()) {
  45697. continue;
  45698. }
  45699. if (!light.canAffectMesh(mesh)) {
  45700. continue;
  45701. }
  45702. this._lightRadiuses[lightIndex] = light.radius;
  45703. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  45704. // GAMMA CORRECTION.
  45705. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  45706. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  45707. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  45708. if (defines["SPECULARTERM"]) {
  45709. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  45710. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  45711. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  45712. }
  45713. // Shadows
  45714. if (scene.shadowsEnabled) {
  45715. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  45716. }
  45717. lightIndex++;
  45718. if (lightIndex === maxSimultaneousLights)
  45719. break;
  45720. }
  45721. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  45722. };
  45723. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  45724. if (this.checkReadyOnlyOnce) {
  45725. if (this._wasPreviouslyReady) {
  45726. return true;
  45727. }
  45728. }
  45729. var scene = this.getScene();
  45730. if (!this.checkReadyOnEveryCall) {
  45731. if (this._renderId === scene.getRenderId()) {
  45732. if (this._checkCache(scene, mesh, useInstances)) {
  45733. return true;
  45734. }
  45735. }
  45736. }
  45737. var engine = scene.getEngine();
  45738. var needNormals = false;
  45739. var needUVs = false;
  45740. this._defines.reset();
  45741. if (scene.texturesEnabled) {
  45742. // Textures
  45743. if (scene.texturesEnabled) {
  45744. if (scene.getEngine().getCaps().textureLOD) {
  45745. this._defines.LODBASEDMICROSFURACE = true;
  45746. }
  45747. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45748. if (!this.albedoTexture.isReady()) {
  45749. return false;
  45750. }
  45751. else {
  45752. needUVs = true;
  45753. this._defines.ALBEDO = true;
  45754. }
  45755. }
  45756. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45757. if (!this.ambientTexture.isReady()) {
  45758. return false;
  45759. }
  45760. else {
  45761. needUVs = true;
  45762. this._defines.AMBIENT = true;
  45763. }
  45764. }
  45765. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45766. if (!this.opacityTexture.isReady()) {
  45767. return false;
  45768. }
  45769. else {
  45770. needUVs = true;
  45771. this._defines.OPACITY = true;
  45772. if (this.opacityTexture.getAlphaFromRGB) {
  45773. this._defines.OPACITYRGB = true;
  45774. }
  45775. }
  45776. }
  45777. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45778. if (!this.reflectionTexture.isReady()) {
  45779. return false;
  45780. }
  45781. else {
  45782. needNormals = true;
  45783. this._defines.REFLECTION = true;
  45784. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45785. this._defines.INVERTCUBICMAP = true;
  45786. }
  45787. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  45788. switch (this.reflectionTexture.coordinatesMode) {
  45789. case BABYLON.Texture.CUBIC_MODE:
  45790. case BABYLON.Texture.INVCUBIC_MODE:
  45791. this._defines.REFLECTIONMAP_CUBIC = true;
  45792. break;
  45793. case BABYLON.Texture.EXPLICIT_MODE:
  45794. this._defines.REFLECTIONMAP_EXPLICIT = true;
  45795. break;
  45796. case BABYLON.Texture.PLANAR_MODE:
  45797. this._defines.REFLECTIONMAP_PLANAR = true;
  45798. break;
  45799. case BABYLON.Texture.PROJECTION_MODE:
  45800. this._defines.REFLECTIONMAP_PROJECTION = true;
  45801. break;
  45802. case BABYLON.Texture.SKYBOX_MODE:
  45803. this._defines.REFLECTIONMAP_SKYBOX = true;
  45804. break;
  45805. case BABYLON.Texture.SPHERICAL_MODE:
  45806. this._defines.REFLECTIONMAP_SPHERICAL = true;
  45807. break;
  45808. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45809. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45810. break;
  45811. }
  45812. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  45813. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  45814. needNormals = true;
  45815. if (this.reflectionTexture.isPMREM) {
  45816. this._defines.USEPMREMREFLECTION = true;
  45817. }
  45818. }
  45819. }
  45820. }
  45821. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45822. if (!this.lightmapTexture.isReady()) {
  45823. return false;
  45824. }
  45825. else {
  45826. needUVs = true;
  45827. this._defines.LIGHTMAP = true;
  45828. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  45829. }
  45830. }
  45831. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45832. if (!this.emissiveTexture.isReady()) {
  45833. return false;
  45834. }
  45835. else {
  45836. needUVs = true;
  45837. this._defines.EMISSIVE = true;
  45838. }
  45839. }
  45840. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45841. if (!this.reflectivityTexture.isReady()) {
  45842. return false;
  45843. }
  45844. else {
  45845. needUVs = true;
  45846. this._defines.REFLECTIVITY = true;
  45847. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  45848. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  45849. }
  45850. }
  45851. }
  45852. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  45853. if (!this.bumpTexture.isReady()) {
  45854. return false;
  45855. }
  45856. else {
  45857. needUVs = true;
  45858. this._defines.BUMP = true;
  45859. if (this.useParallax) {
  45860. this._defines.PARALLAX = true;
  45861. if (this.useParallaxOcclusion) {
  45862. this._defines.PARALLAXOCCLUSION = true;
  45863. }
  45864. }
  45865. }
  45866. }
  45867. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45868. if (!this.refractionTexture.isReady()) {
  45869. return false;
  45870. }
  45871. else {
  45872. needUVs = true;
  45873. this._defines.REFRACTION = true;
  45874. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  45875. if (this.linkRefractionWithTransparency) {
  45876. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45877. }
  45878. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  45879. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  45880. if (this.refractionTexture.isPMREM) {
  45881. this._defines.USEPMREMREFRACTION = true;
  45882. }
  45883. }
  45884. }
  45885. }
  45886. }
  45887. // Effect
  45888. if (scene.clipPlane) {
  45889. this._defines.CLIPPLANE = true;
  45890. }
  45891. if (engine.getAlphaTesting()) {
  45892. this._defines.ALPHATEST = true;
  45893. }
  45894. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45895. this._defines.ALPHAFROMALBEDO = true;
  45896. }
  45897. if (this.useEmissiveAsIllumination) {
  45898. this._defines.EMISSIVEASILLUMINATION = true;
  45899. }
  45900. if (this.linkEmissiveWithAlbedo) {
  45901. this._defines.LINKEMISSIVEWITHALBEDO = true;
  45902. }
  45903. if (this.useLogarithmicDepth) {
  45904. this._defines.LOGARITHMICDEPTH = true;
  45905. }
  45906. if (this.cameraContrast != 1) {
  45907. this._defines.CAMERACONTRAST = true;
  45908. }
  45909. if (this.cameraExposure != 1) {
  45910. this._defines.CAMERATONEMAP = true;
  45911. }
  45912. if (this.overloadedShadeIntensity != 1 ||
  45913. this.overloadedShadowIntensity != 1) {
  45914. this._defines.OVERLOADEDSHADOWVALUES = true;
  45915. }
  45916. if (this.overloadedMicroSurfaceIntensity > 0 ||
  45917. this.overloadedEmissiveIntensity > 0 ||
  45918. this.overloadedReflectivityIntensity > 0 ||
  45919. this.overloadedAlbedoIntensity > 0 ||
  45920. this.overloadedAmbientIntensity > 0 ||
  45921. this.overloadedReflectionIntensity > 0) {
  45922. this._defines.OVERLOADEDVALUES = true;
  45923. }
  45924. // Point size
  45925. if (this.pointsCloud || scene.forcePointsCloud) {
  45926. this._defines.POINTSIZE = true;
  45927. }
  45928. // Fog
  45929. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45930. this._defines.FOG = true;
  45931. }
  45932. if (scene.lightsEnabled && !this.disableLighting) {
  45933. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  45934. }
  45935. if (BABYLON.StandardMaterial.FresnelEnabled) {
  45936. // Fresnel
  45937. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  45938. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45939. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  45940. this._defines.OPACITYFRESNEL = true;
  45941. }
  45942. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  45943. this._defines.EMISSIVEFRESNEL = true;
  45944. }
  45945. needNormals = true;
  45946. this._defines.FRESNEL = true;
  45947. }
  45948. }
  45949. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  45950. this._defines.SPECULAROVERALPHA = true;
  45951. }
  45952. if (this.usePhysicalLightFalloff) {
  45953. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  45954. }
  45955. if (this.useRadianceOverAlpha) {
  45956. this._defines.RADIANCEOVERALPHA = true;
  45957. }
  45958. // Attribs
  45959. if (mesh) {
  45960. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45961. this._defines.NORMAL = true;
  45962. }
  45963. if (needUVs) {
  45964. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45965. this._defines.UV1 = true;
  45966. }
  45967. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45968. this._defines.UV2 = true;
  45969. }
  45970. }
  45971. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  45972. this._defines.VERTEXCOLOR = true;
  45973. if (mesh.hasVertexAlpha) {
  45974. this._defines.VERTEXALPHA = true;
  45975. }
  45976. }
  45977. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45978. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  45979. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  45980. }
  45981. // Instances
  45982. if (useInstances) {
  45983. this._defines.INSTANCES = true;
  45984. }
  45985. }
  45986. // Get correct effect
  45987. if (!this._defines.isEqual(this._cachedDefines)) {
  45988. this._defines.cloneTo(this._cachedDefines);
  45989. scene.resetCachedMaterial();
  45990. // Fallbacks
  45991. var fallbacks = new BABYLON.EffectFallbacks();
  45992. if (this._defines.REFLECTION) {
  45993. fallbacks.addFallback(0, "REFLECTION");
  45994. }
  45995. if (this._defines.REFRACTION) {
  45996. fallbacks.addFallback(0, "REFRACTION");
  45997. }
  45998. if (this._defines.REFLECTIVITY) {
  45999. fallbacks.addFallback(0, "REFLECTIVITY");
  46000. }
  46001. if (this._defines.BUMP) {
  46002. fallbacks.addFallback(0, "BUMP");
  46003. }
  46004. if (this._defines.PARALLAX) {
  46005. fallbacks.addFallback(1, "PARALLAX");
  46006. }
  46007. if (this._defines.PARALLAXOCCLUSION) {
  46008. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  46009. }
  46010. if (this._defines.SPECULAROVERALPHA) {
  46011. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  46012. }
  46013. if (this._defines.FOG) {
  46014. fallbacks.addFallback(1, "FOG");
  46015. }
  46016. if (this._defines.POINTSIZE) {
  46017. fallbacks.addFallback(0, "POINTSIZE");
  46018. }
  46019. if (this._defines.LOGARITHMICDEPTH) {
  46020. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  46021. }
  46022. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  46023. if (this._defines.SPECULARTERM) {
  46024. fallbacks.addFallback(0, "SPECULARTERM");
  46025. }
  46026. if (this._defines.OPACITYFRESNEL) {
  46027. fallbacks.addFallback(1, "OPACITYFRESNEL");
  46028. }
  46029. if (this._defines.EMISSIVEFRESNEL) {
  46030. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  46031. }
  46032. if (this._defines.FRESNEL) {
  46033. fallbacks.addFallback(3, "FRESNEL");
  46034. }
  46035. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  46036. fallbacks.addCPUSkinningFallback(0, mesh);
  46037. }
  46038. //Attributes
  46039. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46040. if (this._defines.NORMAL) {
  46041. attribs.push(BABYLON.VertexBuffer.NormalKind);
  46042. }
  46043. if (this._defines.UV1) {
  46044. attribs.push(BABYLON.VertexBuffer.UVKind);
  46045. }
  46046. if (this._defines.UV2) {
  46047. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46048. }
  46049. if (this._defines.VERTEXCOLOR) {
  46050. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46051. }
  46052. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  46053. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  46054. // Legacy browser patch
  46055. var shaderName = "pbr";
  46056. if (!scene.getEngine().getCaps().standardDerivatives) {
  46057. shaderName = "legacypbr";
  46058. }
  46059. var join = this._defines.toString();
  46060. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  46061. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  46062. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  46063. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  46064. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  46065. "vFogInfos", "vFogColor", "pointSize",
  46066. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  46067. "mBones",
  46068. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  46069. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  46070. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  46071. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  46072. "logarithmicDepthConstant",
  46073. "vSphericalX", "vSphericalY", "vSphericalZ",
  46074. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  46075. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  46076. "vMicrosurfaceTextureLods", "vLightRadiuses"
  46077. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  46078. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  46079. ], join, fallbacks, this.onCompiled, this.onError);
  46080. }
  46081. if (!this._effect.isReady()) {
  46082. return false;
  46083. }
  46084. this._renderId = scene.getRenderId();
  46085. this._wasPreviouslyReady = true;
  46086. if (mesh) {
  46087. if (!mesh._materialDefines) {
  46088. mesh._materialDefines = new PBRMaterialDefines();
  46089. }
  46090. this._defines.cloneTo(mesh._materialDefines);
  46091. }
  46092. return true;
  46093. };
  46094. PBRMaterial.prototype.unbind = function () {
  46095. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  46096. this._effect.setTexture("reflection2DSampler", null);
  46097. }
  46098. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  46099. this._effect.setTexture("refraction2DSampler", null);
  46100. }
  46101. _super.prototype.unbind.call(this);
  46102. };
  46103. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46104. this._effect.setMatrix("world", world);
  46105. };
  46106. PBRMaterial.prototype.bind = function (world, mesh) {
  46107. this._myScene = this.getScene();
  46108. // Matrices
  46109. this.bindOnlyWorldMatrix(world);
  46110. // Bones
  46111. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46112. if (this._myScene.getCachedMaterial() !== this) {
  46113. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  46114. if (BABYLON.StandardMaterial.FresnelEnabled) {
  46115. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  46116. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  46117. }
  46118. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  46119. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  46120. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  46121. }
  46122. }
  46123. // Textures
  46124. if (this._myScene.texturesEnabled) {
  46125. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46126. this._effect.setTexture("albedoSampler", this.albedoTexture);
  46127. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  46128. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  46129. }
  46130. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46131. this._effect.setTexture("ambientSampler", this.ambientTexture);
  46132. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  46133. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  46134. }
  46135. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46136. this._effect.setTexture("opacitySampler", this.opacityTexture);
  46137. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  46138. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  46139. }
  46140. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46141. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  46142. if (this.reflectionTexture.isCube) {
  46143. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  46144. }
  46145. else {
  46146. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  46147. }
  46148. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  46149. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  46150. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  46151. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  46152. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  46153. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  46154. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  46155. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  46156. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  46157. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  46158. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  46159. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  46160. }
  46161. }
  46162. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46163. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  46164. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  46165. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  46166. }
  46167. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46168. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  46169. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  46170. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  46171. }
  46172. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46173. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  46174. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  46175. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  46176. }
  46177. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  46178. this._effect.setTexture("bumpSampler", this.bumpTexture);
  46179. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  46180. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  46181. }
  46182. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46183. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  46184. var depth = 1.0;
  46185. if (this.refractionTexture.isCube) {
  46186. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  46187. }
  46188. else {
  46189. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  46190. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  46191. if (this.refractionTexture.depth) {
  46192. depth = this.refractionTexture.depth;
  46193. }
  46194. }
  46195. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  46196. }
  46197. if ((this.reflectionTexture || this.refractionTexture)) {
  46198. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  46199. }
  46200. }
  46201. // Clip plane
  46202. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  46203. // Point size
  46204. if (this.pointsCloud) {
  46205. this._effect.setFloat("pointSize", this.pointSize);
  46206. }
  46207. // Colors
  46208. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  46209. // GAMMA CORRECTION.
  46210. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  46211. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  46212. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46213. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  46214. // GAMMA CORRECTION.
  46215. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  46216. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  46217. // GAMMA CORRECTION.
  46218. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  46219. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  46220. }
  46221. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  46222. // GAMMA CORRECTION.
  46223. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  46224. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  46225. // Lights
  46226. if (this._myScene.lightsEnabled && !this.disableLighting) {
  46227. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  46228. }
  46229. // View
  46230. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  46231. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  46232. }
  46233. // Fog
  46234. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  46235. this._lightingInfos.x = this.directIntensity;
  46236. this._lightingInfos.y = this.emissiveIntensity;
  46237. this._lightingInfos.z = this.environmentIntensity;
  46238. this._lightingInfos.w = this.specularIntensity;
  46239. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  46240. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  46241. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  46242. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  46243. this._cameraInfos.x = this.cameraExposure;
  46244. this._cameraInfos.y = this.cameraContrast;
  46245. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  46246. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  46247. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  46248. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  46249. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  46250. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  46251. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  46252. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  46253. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  46254. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  46255. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  46256. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  46257. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  46258. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  46259. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  46260. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  46261. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  46262. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  46263. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  46264. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  46265. // Log. depth
  46266. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  46267. }
  46268. _super.prototype.bind.call(this, world, mesh);
  46269. this._myScene = null;
  46270. };
  46271. PBRMaterial.prototype.getAnimatables = function () {
  46272. var results = [];
  46273. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  46274. results.push(this.albedoTexture);
  46275. }
  46276. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  46277. results.push(this.ambientTexture);
  46278. }
  46279. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  46280. results.push(this.opacityTexture);
  46281. }
  46282. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  46283. results.push(this.reflectionTexture);
  46284. }
  46285. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  46286. results.push(this.emissiveTexture);
  46287. }
  46288. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  46289. results.push(this.reflectivityTexture);
  46290. }
  46291. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  46292. results.push(this.bumpTexture);
  46293. }
  46294. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  46295. results.push(this.lightmapTexture);
  46296. }
  46297. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  46298. results.push(this.refractionTexture);
  46299. }
  46300. return results;
  46301. };
  46302. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46303. if (forceDisposeTextures) {
  46304. if (this.albedoTexture) {
  46305. this.albedoTexture.dispose();
  46306. }
  46307. if (this.ambientTexture) {
  46308. this.ambientTexture.dispose();
  46309. }
  46310. if (this.opacityTexture) {
  46311. this.opacityTexture.dispose();
  46312. }
  46313. if (this.reflectionTexture) {
  46314. this.reflectionTexture.dispose();
  46315. }
  46316. if (this.emissiveTexture) {
  46317. this.emissiveTexture.dispose();
  46318. }
  46319. if (this.reflectivityTexture) {
  46320. this.reflectivityTexture.dispose();
  46321. }
  46322. if (this.bumpTexture) {
  46323. this.bumpTexture.dispose();
  46324. }
  46325. if (this.lightmapTexture) {
  46326. this.lightmapTexture.dispose();
  46327. }
  46328. if (this.refractionTexture) {
  46329. this.refractionTexture.dispose();
  46330. }
  46331. }
  46332. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46333. };
  46334. PBRMaterial.prototype.clone = function (name) {
  46335. var _this = this;
  46336. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46337. };
  46338. PBRMaterial.prototype.serialize = function () {
  46339. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46340. serializationObject.customType = "BABYLON.PBRMaterial";
  46341. return serializationObject;
  46342. };
  46343. // Statics
  46344. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46345. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46346. };
  46347. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  46348. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  46349. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  46350. PBRMaterial._scaledReflection = new BABYLON.Color3();
  46351. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  46352. __decorate([
  46353. BABYLON.serialize()
  46354. ], PBRMaterial.prototype, "directIntensity", void 0);
  46355. __decorate([
  46356. BABYLON.serialize()
  46357. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46358. __decorate([
  46359. BABYLON.serialize()
  46360. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46361. __decorate([
  46362. BABYLON.serialize()
  46363. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46364. __decorate([
  46365. BABYLON.serialize()
  46366. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46367. __decorate([
  46368. BABYLON.serialize()
  46369. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  46370. __decorate([
  46371. BABYLON.serialize()
  46372. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  46373. __decorate([
  46374. BABYLON.serialize()
  46375. ], PBRMaterial.prototype, "cameraExposure", void 0);
  46376. __decorate([
  46377. BABYLON.serialize()
  46378. ], PBRMaterial.prototype, "cameraContrast", void 0);
  46379. __decorate([
  46380. BABYLON.serializeAsColor3()
  46381. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  46382. __decorate([
  46383. BABYLON.serialize()
  46384. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  46385. __decorate([
  46386. BABYLON.serializeAsColor3()
  46387. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  46388. __decorate([
  46389. BABYLON.serialize()
  46390. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  46391. __decorate([
  46392. BABYLON.serializeAsColor3()
  46393. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  46394. __decorate([
  46395. BABYLON.serialize()
  46396. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  46397. __decorate([
  46398. BABYLON.serializeAsColor3()
  46399. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  46400. __decorate([
  46401. BABYLON.serialize()
  46402. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  46403. __decorate([
  46404. BABYLON.serializeAsColor3()
  46405. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  46406. __decorate([
  46407. BABYLON.serialize()
  46408. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  46409. __decorate([
  46410. BABYLON.serialize()
  46411. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  46412. __decorate([
  46413. BABYLON.serialize()
  46414. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  46415. __decorate([
  46416. BABYLON.serializeAsTexture()
  46417. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46418. __decorate([
  46419. BABYLON.serializeAsTexture()
  46420. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46421. __decorate([
  46422. BABYLON.serializeAsTexture()
  46423. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46424. __decorate([
  46425. BABYLON.serializeAsTexture()
  46426. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46427. __decorate([
  46428. BABYLON.serializeAsTexture()
  46429. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46430. __decorate([
  46431. BABYLON.serializeAsTexture()
  46432. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46433. __decorate([
  46434. BABYLON.serializeAsTexture()
  46435. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46436. __decorate([
  46437. BABYLON.serializeAsTexture()
  46438. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46439. __decorate([
  46440. BABYLON.serializeAsTexture()
  46441. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46442. __decorate([
  46443. BABYLON.serializeAsColor3("ambient")
  46444. ], PBRMaterial.prototype, "ambientColor", void 0);
  46445. __decorate([
  46446. BABYLON.serializeAsColor3("albedo")
  46447. ], PBRMaterial.prototype, "albedoColor", void 0);
  46448. __decorate([
  46449. BABYLON.serializeAsColor3("reflectivity")
  46450. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46451. __decorate([
  46452. BABYLON.serializeAsColor3("reflection")
  46453. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46454. __decorate([
  46455. BABYLON.serializeAsColor3("emissive")
  46456. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46457. __decorate([
  46458. BABYLON.serialize()
  46459. ], PBRMaterial.prototype, "microSurface", void 0);
  46460. __decorate([
  46461. BABYLON.serialize()
  46462. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46463. __decorate([
  46464. BABYLON.serialize()
  46465. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46466. __decorate([
  46467. BABYLON.serializeAsFresnelParameters()
  46468. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  46469. __decorate([
  46470. BABYLON.serializeAsFresnelParameters()
  46471. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  46472. __decorate([
  46473. BABYLON.serialize()
  46474. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46475. __decorate([
  46476. BABYLON.serialize()
  46477. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  46478. __decorate([
  46479. BABYLON.serialize()
  46480. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46481. __decorate([
  46482. BABYLON.serialize()
  46483. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  46484. __decorate([
  46485. BABYLON.serialize()
  46486. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46487. __decorate([
  46488. BABYLON.serialize()
  46489. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46490. __decorate([
  46491. BABYLON.serialize()
  46492. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46493. __decorate([
  46494. BABYLON.serialize()
  46495. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46496. __decorate([
  46497. BABYLON.serialize()
  46498. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  46499. __decorate([
  46500. BABYLON.serialize()
  46501. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46502. __decorate([
  46503. BABYLON.serialize()
  46504. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46505. __decorate([
  46506. BABYLON.serialize()
  46507. ], PBRMaterial.prototype, "useParallax", void 0);
  46508. __decorate([
  46509. BABYLON.serialize()
  46510. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46511. __decorate([
  46512. BABYLON.serialize()
  46513. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46514. __decorate([
  46515. BABYLON.serialize()
  46516. ], PBRMaterial.prototype, "disableLighting", void 0);
  46517. __decorate([
  46518. BABYLON.serialize()
  46519. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  46520. return PBRMaterial;
  46521. })(BABYLON.Material);
  46522. BABYLON.PBRMaterial = PBRMaterial;
  46523. })(BABYLON || (BABYLON = {}));
  46524. 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..maxSimultaneousLights]\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..maxSimultaneousLights]\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..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..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..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..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..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..3]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb); \n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif (microSurface>0.5)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0 ,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0 ,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  46525. 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"};
  46526. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:!(o.z-i>e.z)},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;r>s;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return r>=-n&&n>=r},t.ToHex=function(t){var i=t.toString(16);return 15>=t?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,s=t.g+(i.g-t.g)*r,e=t.b+(i.b-t.b)*r;return new n(o,s,e)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),s=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,s)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n(-this.x,-this.y)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;return s=s>r.y?r.y:s,s=s<i.y?i.y:s,new n(o,s)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r;return new n(o,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];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 a(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,a=o.y,m=u.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+a,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=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.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],b=M.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))),_.x=l,_.y=x,_.z=z,_.normalize(),n.CrossToRef(_,R,b),b.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,n.Dot(b,m)<0&&(c=Math.PI+c,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=c,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){this.width=t,this.height=i}return t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return t?this.width===t.width&&this.height===t.height:!1},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t}();t.Size=h;var a=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=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,b=-(s*v-e*g+h*T),F=1/(i*R+n*_+r*M+o*b),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*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*P)*F,t.m[6]=-(i*A-r*Z+o*C)*F,t.m[10]=(i*L-n*Z+o*S)*F,t.m[14]=-(i*P-n*C+r*S)*F,t.m[3]=-(n*I-r*q+o*E)*F,t.m[7]=(i*I-r*D+o*V)*F,t.m[11]=-(i*q-n*D+o*W)*F,t.m[15]=(i*E-n*V+r*W)*F,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],b=t.m[7],F=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*F+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*b+s*P+e*I,i[n+4]=h*v+a*R+u*F+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*b+u*P+m*I,i[n+8]=y*v+c*R+p*F+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*b+p*P+f*I,i[n+12]=l*v+x*R+z*F+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*b+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,h=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=h*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 a.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){\nvar o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),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){a.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 a,h=new s(0,0,0);i.decompose(o,e,h);var u=new s(0,0,0),m=new a,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=a.Slerp(e,m,r),f=s.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=u;var m=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=u.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],a=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,a,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=m;var y=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=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new m(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=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(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=p;var f=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=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var l=t.Orientation,x=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=x;var z=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=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.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?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=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 z(e,h,a),m=u.angle.radians()/s;u.orientation===l.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,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),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=w;var v=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=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,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=d;var g=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=g;var T=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=T;var R=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=R;var _=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=_;var M=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 a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  46527. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  46528. module.exports = BABYLON;
  46529. };